You k ow that sense of relief when it clicks on your head that you survived? Your brain is flooding with dopamine and your getting a rush of the combination of adrenaline from your "fight or flight" response and the happiness of knowing your continued existence.
This overwhelming rush of intense emotion leads to giggling in some. I know I giggle the more uncomfortable or in pain I get.
I'm going with coping mechanism. I laughed my way all the way through the film version of Sweeney Todd with Johnny Depp. The more blood there was, the harder I laughed. Not a horror movie, I know, but it's my story.
Remember the "ridikulus" spell from Harry Potter? Same idea I think. Laugh at your fears and they no longer have hold over you.
We laugh for two reasons: to show understanding (comedy, good for group cohesion) and to relieve stress after something scary (you just barely out ran a tiger, or watched a scary movie).
Laughing produces "feel-good" endorphins that theoretically relieve stress. It's good to get the body back to normal after high stress because stress is hard on the body. And it's good for bonding because having positive experiences together can encourage people to work together.
Ever had a friend make you jump?
Like pop out from behind a door and shout boo?
It scares you right but then after you laugh and call them some obscenity.
I'm sure the same applies here.