Muscle spasms and cramps occur when a voluntary muscle contracts on it own. The difference is the intensity of the contraction.
Voluntary muscles are ones that you consciously control to create movement. As you move, voluntary muscles contract and become tighter. They then relax when the movement is over. However, sometimes a muscle, or a few muscle fibres, contracts on its own, causing a muscle spasm or cramp.
Spasm vs. Cramp
The difference between a muscle spasm and a muscle cramp is the force of the contraction. If a muscle quickly contracts and releases without pain, it is a spasm. A prolonged and painful contraction is a cramp.
According to eorthopod.com, the exact cause of muscle cramps isn't known, but they can occur if you don't stretch enough, the muscle is tired, or the muscle isn't getting enough oxygen. Other factors may include heat, dehydration, or not enough salt and minerals (electrolytes).
According to eorthopod.com, the best prevention is stretching, drinking plenty of fluids, and not overexercising, especially in hot weather.
Sometimes muscle spasm or cramp may be a symptom of illness or side effect of medication. Consult your health care provider as appropriate.