It only happens when there is a moment of sheer panic before you die.
For example, if you get shot in the head from behind your life will not flash before your eyes. But if you are drowning, then possibly.
What scientists believe it is is looking back through your memories, trying to find something that can help your situation. A lot of memories
You Might not even know you had.
One case a few years ago was of a man who was attacked by a shark. In his last moments his "life" flashed before his eyes and he remembered once walking in on his friend who was watching a show on sharks. At that point, they were saying that putting your fists into it's gills could make the shark let go of you.
All this came flooding back to the man in a matter of seconds, and he managed to save himself.