It is due to the reflex action. Reflex is “an involuntary action performed by muscles under the direction of spinal cord in response to the stimulus”. In short, reflex actions are automatic responses to stimulus. They are of definite and mechanical type.
Some other example reflex action:
(a) Narrowing of the pupil of the eye when strong light falls upon it.
(b) When a hot object is touched accidentally by our hand, it is withdrawn at once.
© Flow of bile from the gall bladder into the duodenum.
(d) Opening of mouth on hearing a loud report.