Usually it is done deliberately, to wind up teachers. You could try an experiment if you like…
Seriously though, I don’t know. There are some theories that it may be important for helping to cool down the body or to provide an inrush of oxygen in certain circumstances.
It’s quite a hard thing to investigate because everybody yawns, so you can’t do tests on people who do it and people who don’t. Though I wonder if there are some people who do it more than others – that might give some clues.
It’s a good question, and I don’t know the answer. I went to the wikipedia page on the topic which seems quite good. You can see that a number of different reasons have been put forward, but there doesn’t seem to be decisive evidence in favour of any particular reason. One reason might be to communicate to other people, and there are signs that we pick up on yawning as a social signal – yawning is contagious as you’ve probably noticed. Another reason might be a physiological response to tiredness or stress. I didn’t find this explanation particularly convincing, and I’d want to see some good evidence for it. How could you design an experiment to test the idea? Can we find a way to make people yawn more or less? If we could perhaps we could see whether the amount of yawning affected oxygen or carbon dioxide levels in the blood, or the temperature of the brain.
It’s interesting that one of the more authoritative sources on the wiki page is a study suggesting children with autism don’t show contagious yawning. Autism is thought to be a problem affecting empathy – the ability (loosely speaking) to put yourself in someone else’s shoes. So the absence of contagious yawning in autistic children might suggest that it is driven in part by social communication and empathy.
…oooh! lets start with a tough one! A lot of people who know about these things seem to think it’s to do with oxygen and the brain, particularly not having enough of it when you are tired…You suck in air when you yawn big time and get an instant oxygen hit. There might be an evolutionary reason why we yawn when we see other people yawning – if our ancient ancestors couldn’t communicate verbally, this might show that the group needs to kip before heading out for another tough mammoth hunt – but that might be nonsense too.