I created a simple snake game after following some simple tutorials on YouTube. 

The problem is that the game does not have a pause function (e.g. when pressing P the game should pause/resume) and when the snake hits the border of the canvas the game restarts itself (but that is another problem). 

Here is the complete code I have of the game: <https://pastebin.com/URaDxSvF>

The pause-related functions I've created:

```
function gamePaused{ /**i need help on this**/ }

function keyDown(e) {
  if (e.keyCode == 80) pauseGame();
}

function pauseGame() {
  if (!gamePaused) {
    game = clearTimeout(game);
    gamePaused = true;
  } else if (gamePaused) {
    game = setTimeout(loop, 1000 / 30);
    gamePaused = false;
  }
}

```
['https://Stackoverflow.com/questions/43814422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7971087/']
Create a Boolean variable called paused and set it to true if the player presses p, Then put an if statement around the loop that runs your game. and say if (!paused){run loop}

You can create a toggle pause function for when p is pressed.

```
function togglePause()
{
    if (!paused)
    {
        paused = true;
    } else if (paused)
    {
       paused= false;
    }

}

```

You also need to create an event listener for when p is pressed
Like this 

```
window.addEventListener('keydown', function (e) {
var key = e.keyCode;
if (key === 80)// p key
{
    togglePause();
}
});

```

up the top where you have Game objects and constants put in paused = false, and in your loop function do this

```
 draw(); 
if(!paused)
{ 
update(); 
}

```
Your game loop is not based on `setTimeout`, but on `requestAnimationFrame`. So setting and clearing a timer will not change anything.

Secondly, you did not bind your `keyDown` function to any event, so it will never get invoked.

### Solution:

Have a look at your `loop` function: it calls itself asynchronously, which provides the animation. You need to stop that loop to effectively introduce a pause:

```
function loop() {
    if (gamePaused) return; // <--- stop looping
    update();
    draw();
    window.requestAnimationFrame(loop, canvas);
}

```

Define the new variable upon page load, and bind your function to the `keyDown` event:

```
var gamePaused = false;
document.addEventListener('keydown', keyDown);

```

And your `pauseGame` function would look like this:

```
function pauseGame() {
    gamePaused = !gamePaused; // toggle the gamePaused value (false <-> true)
    if (!gamePaused) loop(); // restart loop
}

```