Actually, we do not know the answer. One theory is that it is to control heat loss. A long, bare leg loses a lot more heat that a leg that is tucked up into insulating feathers. Especially for wading birds that spend a lot of time in the water, this heat loss can be a big problem. It means that they must have a lot more food to supply the extra energy. Reducing the heat loss would mean that the bird could survive on less food. Recent studies have shown that as the temperature increases, birds are more likely to stand on both legs. As it gets colder, they are more likely to stand on one leg.
Another theory is that birds don't go fully asleep. We know that for dolphins and ducks, one half of the brain sleeps while the other half remains awake. The same may be true for other birds. The half of the brain that stays awake would maintain the balance on one leg, while the other leg rested.
This is one of the aspects of science that I really like. It is wonderful that there are still so many mysteries left for us to explore.