How do flame tests give off color if they only emit the colors when the electrons return to ground state?
The flame area is a violent place due to high temperature favoring ionization. The color appears due to the dynamic process of the formation of short-lived species formed briefly in the flame. As we are burning hydrocarbons, they get split into unstable radicals easily loosing unpaired electrons. In the area of the flame enriched with electrons metal ions from the probe such as $\ce{Na+}$ are reduced to the metal atoms:

$$\ce{Na+ + e- -&gt; Na^0}$$

which are emitting yellow light in a form of observable doublet of spectral lines ($λ_1 = \pu{589.0 nm}$, $λ_2 = \pu{589.5 nm}$) arising from the electronic transitions $\ce{3s^1 -&gt; 3p^1}$. Note that it is the metal atom, not the ion, that is responsible for the emission of light of the given color.

So, as long as we keep the test probe (metal salt) in the flame, we can observe spectral lines of the given element as both conditions are fulfilled (energy supply (heat) and reducing atmosphere (free electrons from the fuel)). By taking the sample out of the flame, electron transitions are no longer possible as there is neither metal atoms capable of any, nor enough energy to promote the electron to the higher level.