During a recent ride my tire went flat on my tri bike. I was about to change the tube but thought I'd just put some air in the flat tire first. Amazingly it held air for the rest of my ride (another 2 hours). Why does this happen?
When I was a child I learned that with a flat you would first pump up the tube and wait overnight (if you had the time) before going through the effort of patching it.
As part of that pump-up action you would check the valve was tight.
Only if flat or soft again the next day we would spend the time and effort patching.
Very often it is indeed the valve which has a problem. Different types of valves can have different problems, in the ones we used there is a ring pushing the actual valve in position and it is rather likely for that ring to be less than tight. And those valves we used when I was a child had a bit of rubber tube, which often failed, so it was not uncommon to take the valve out and replace that tube. These days I often replace the current valve with a new one, just to make sure.
Other kinds of valve have a different system of closure and those are really likely to be tightened properly when you finish pumping or may re-set themselves when the tube comes to full power.
Slow leaks are often slow enough to hold air for quite a while. Do check the outside of the tire if you want to keep riding after a flat, as if a sharp item is logged in the tire, it will make for a much worse set of holes in the tube. There are different approaches. If you will replace the tube anyhow, you may want to leave the hole-maker in, to plug the hole. But if you need to patch the tube, do not ride any farther with a sharp in the tire.
I own a bike cart which has been allowed to have a slow leak for more than a decade, more likely closer to 25 years, as the loss of air was so slow that we would never be surprised by a flat while underway. I have now a new tube for it, as it is now no longer a slow leak, it was flat in about 10 minutes. (But I have to admit that I have not checked the valve yet.)
So yes, if you have the time, first just pump (and check/properly close the valve) when you have a flat.