requestAnimationFrame runs twice as fast after cancelAnimtionFrame

261 Views Asked by At

I've been staring at my code for so long but i don't seem to understand what is happening. Whenever the game ends, I do a cancelAnimationFrame to stop the game. Then I boot up the menu again.

Now the problem is that when I call requestAnimationFrame again, it seems like the code is calling it two times (the game runs doubly fast).

The following is my code:

This is the startup:

var areaJogo = {
    beginGame: function(type) {
        //...
        this.myReq = requestAnimationFrame(updateArea);
        //...
    }
}

And this is the main function(for animation):

function updateArea(){
    areaJogo.myReq=requestAnimationFrame(updateArea);

    //....

    if(/*conditionLoseGame*/) {
        stop();  
    }
}

function stop() {
    cancelAnimationFrame(areaJogo.myReq);

    areaJogo.myReq=undefined;
}

Mind you these are the only times requestAnimationFrame and cancelAnimationFrame are used in the code. Thanks!

1

There are 1 best solutions below

0
Nuno Alves On

I have found the problem.

The reason why it was being called is because I had done a button in JavaScript to start the game.

To do this, I had to do a addeventlistener whenever I booted the menu. What I did wrong was forgetting to do cleareventlistener upon clicking the button.