Why is cancelAnimationFrame not working?

回眸只為那壹抹淺笑 提交于 2021-02-07 20:45:29

问题


Refer to this fiddle - http://jsfiddle.net/rnqLfz14/28/

[ This code is not mine - 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. Got any suggestions? I have scratched my head over it for a long time now please any suggestions would be appreciated.


回答1:


When the condition for stop() is fulfilled, stop() is called but the code continues so a new rAF will be requested.

Just add a return after the stop call to prevent this from happening (or use an 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



来源:https://stackoverflow.com/questions/30290404/why-is-cancelanimationframe-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!