Why a held pause key can restart your game

Imagine stopping a browser game just before a difficult jump. You press P, take a moment to lift your finger, and the game is already running again. One physical press can deliver several keyboard events. In this experiment, feed the same press to two copies of a pause menu and see exactly where they disagree.

Try a tap, then a hold

Both copies begin in play. Select the keyboard pad, tap the letter P once and release it. Both copies should pause. Reset them, select the pad again and hold P until the first counter moves more than once. Then release. A keyboard with repeat switched off may give you just one event. The replay button works on a touch screen and always supplies the same sequence.

Every keydown

Playing · 0 switches

First keydown only

Playing · 0 switches

Input events in order

Waiting for input.

Read the two counters

The replay starts a fresh trial. It supplies one initial keydown, three repeating keydowns and one keyup. The first menu changes state four times and ends up playing. The second changes once and stays paused. The release appears in the event list and changes neither menu. A shorter hold on your own keyboard can leave both menus paused even when the first one switched three times. Looking at the final screen alone hides that error.

Give each action a rule

For a pause command, inspect the repeat flag on the keydown event. Switch the menu only when the event belongs to the chosen key and repeat is false. For walking, a different rule works better. Remember that the movement key is down, let the game loop advance the character while it stays down, and clear the flag on release. Otherwise the pace of movement can depend on the repeat delay set on the player's computer.

To check a fix, try two separate quick taps after a reset. Both menus should switch twice and finish in play. Next, run the held-key replay. A pause command that passes both trials accepts a genuine second press while ignoring the extra events from the first one.