This phenomenon is known as a myoclonic jerk, and it has been suggested that it is a throwback to our remotest ancestors who lived in the wild, and that humans developed this reflex to prevent themselves falling off the branches of trees as they dozed off.
But this is a romantic folk story for which there seems to be no scientific proof. What is known is that sleep occurs in four stages. There is the first very light, half dozing state, then a light sleep stage followed by a third somewhat deeper one which ends in the deepest of all which is stage four. These stages can be demonstrated on an ECG machine, because the brains electrical impulses make different patterns as the sleeper passes through each stage.
Sometimes, as a person descends from stage three sleep to stage four there is a sudden upsurge of brain activity. This sends out a little burst of electrical impulses which go to all the muscles and make them contract in a sharp spasm.
Not everyone experiences this jerking although it happens to about two thirds of the population.