ClearInterval() is not working?

I’m making a snake game and right now I’m trying to stop the game with a clearInterval() function when the snake hits the boarder of the canvas. I have the function checkForCollision() that checks the position of the snake.

function checkForCollision(newHeadX, newHeadY) {
    //check the new head position to see if its collided
    if(newHeadX < 0 || newHeadX > cvs.width ||
       newHeadY < 0 || newHeadY > cvs.height) clearInterval(startGame);

You can see it takes the position of the snakes head is a parameter. The function is called every second within the runGame function, which is set to repeat every second from the startGame interval.

let startGame = setInterval(rungame, 1000);

You can see the logic that runs the snake movement here

switch(direction) {
        case "left":
            newHeadX -= unit; // Grab the next possible position
            checkForCollision(newHeadX, newHeadY) // check that future position
            drawSnake('#858585'); //undraw the snake
            snake.unshift({x: newHeadX, y: newHeadY}); // add the new head
            snake.pop(); // remove the tail
            drawSnake('limegreen'); //draw the snake

Now when the newHeadX gets below zero. I watch the condition execute clearInterval(rungame)
This should freeze the game before the snake can move outside the canvas. But it doesn’t? Even though I watch the condition execute the clear interval?

The clearInterval is working. When an out of bounds condition occurs, the game function doesn’t get called again.

Where the problem is happening is that after checkForCollision finds an invalid location, the switch code still carries on to draw the snake in the invalid location.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.