1

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!

Nuno Alves
  • 11
  • 1
  • 2
  • Use your debugger. Set a breakpoint in your `updateArea` function and inspect the stack-trace to see who is calling it a second time and why. Also, don't call `requestAnimationFrame` at the start of your function, instead call it before you return from it so you don't need to call `cancelAnimationFrame`. – Dai Feb 03 '18 at 00:22
  • The debugger seems to just say it's being called only from `updateArea` and the reason being because it's... well being called there. I've also tried changing the positions of `requestAnimationFrame` and the returns plus the `cancelAnimationFrame` but it seems that it remains the same unfortunately – Nuno Alves Feb 03 '18 at 00:44
  • Please post a Minimal, Complete, and Verifiable example on jsFiddle. – Dai Feb 03 '18 at 01:09

1 Answers1

0

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Nuno Alves
  • 11
  • 1
  • 2