Well if these are happening to you, I can diagnose you.
They're called hypnic jerks. They happen just before you fall asleep and can cause panic and are also accompanied with a feeling of falling and legs shooting out.
You can prevent them by reducing caffeine, nicotine, and alcohol intake, reducing stress and not exercising 2-3 hours before going to bed.