requestAnimationFrame在cancelAnimtionFrame之后运行两倍

时间:2018-02-03 00:17:42

标签: javascript html5 requestanimationframe cancelanimationframe

我一直盯着我的代码这么长时间,但我似乎不明白发生了什么。 每当游戏结束时,我都会使用cancelAnimationFrame来停止游戏。然后我再次启动菜单。

现在的问题是,当我再次调用requestAnimationFrame时,似乎代码正在调用它两次(游戏运行速度加倍)。

以下是我的代码:

这是创业公司:

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

这是主要功能(用于动画):

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

    //....

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

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

    areaJogo.myReq=undefined;
}

请注意,这些是在代码中使用requestAnimationFrame和cancelAnimationFrame的唯一次数。谢谢!

1 个答案:

答案 0 :(得分: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.