简体   繁体   English

为什么cancelAnimationFrame 不起作用?

[英]Why is cancelAnimationFrame not working?

Refer to this fiddle - http://jsfiddle.net/rnqLfz14/28/参考这个小提琴 - http://jsfiddle.net/rnqLfz14/28/

[ This code is not mine - http://www.isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing ] [ 此代码不是我的 - http://www.isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing ]

//....

function stop() {
    running = false;
    started = false;
    cancelAnimationFrame(frameID);
}

//...

function mainLoop(timestamp) {
    // Throttle the frame rate.
    if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
        frameID = requestAnimationFrame(mainLoop);
        return;
    }
    delta += timestamp - lastFrameTimeMs;
    lastFrameTimeMs = timestamp;

    begin(timestamp, delta);

    if (timestamp > lastFpsUpdate + 1000) {
        fps = 0.25 * framesThisSecond + 0.75 * fps;

        lastFpsUpdate = timestamp;
        framesThisSecond = 0;
    }
    framesThisSecond++;

    var numUpdateSteps = 0;
    while (delta >= timestep) {
        update(timestep);
        delta -= timestep;
        if (++numUpdateSteps >= 240) {
            panic();
            break;
        }
    }

    draw(delta / timestep);

    T.textContent = timestamp;

    if (timestamp >= 6000.0) {
        T.textContent = "Stopped!";
        stop();
    }

    end(fps);

    frameID = requestAnimationFrame(mainLoop);
}
//...

The cancelAnimationFrame function is not stopping the animating loop. cancelAnimationFrame 函数不会停止动画循环。 Got any suggestions?有什么建议吗? I have scratched my head over it for a long time now please any suggestions would be appreciated.我已经为此挠头很久了,请提供任何建议,我们将不胜感激。

When the condition for stop() is fulfilled, stop() is called but the code continues so a new rAF will be requested.当满足stop()的条件时,会调用stop()但代码会继续,因此将请求新的 rAF。

Just add a return after the stop call to prevent this from happening (or use an else ):只需在 stop 调用后添加 return 以防止发生这种情况(或使用else ):

...
if (timestamp >= 6000.0) {
    T.textContent = "Stopped!";
    stop();  // stop() is just a sub-routine here and will continue after being called
    return;  // <--- here
}
...

Modified fiddle修改后的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM