Javascript 为什么cancelAnimationFrame不工作?

Javascript 为什么cancelAnimationFrame不工作?,javascript,html,animation,requestanimationframe,Javascript,Html,Animation,Requestanimationframe,参考这把小提琴- [此代码不是我的-] /。。。。 函数停止(){ 运行=错误; 开始=错误; 取消动画帧(帧ID); } //... 函数mainLoop(时间戳){ //限制帧速率。 如果(时间戳最新更新+1000){ fps=0.25*frames秒+0.75*fps; lastFpsUpdate=时间戳; 帧秒=0; } framesthissond++; var numUpdateSteps=0; 而(增量>=timestep){ 更新(时间步); delta-=时间步长; 如果(++

参考这把小提琴-

[此代码不是我的-]

/。。。。
函数停止(){
运行=错误;
开始=错误;
取消动画帧(帧ID);
}
//...
函数mainLoop(时间戳){
//限制帧速率。
如果(时间戳最新更新+1000){
fps=0.25*frames秒+0.75*fps;
lastFpsUpdate=时间戳;
帧秒=0;
}
framesthissond++;
var numUpdateSteps=0;
而(增量>=timestep){
更新(时间步);
delta-=时间步长;
如果(++numUpdateSteps>=240){
恐慌();
打破
}
}
绘制(增量/时间步长);
T.textContent=时间戳;
如果(时间戳>=6000.0){
T.textContent=“停止!”;
停止();
}
完(fps);
frameID=requestAnimationFrame(主循环);
}
//...

cancelAnimationFrame函数不会停止动画循环。有什么建议吗?我已经为它挠头很久了,现在请任何建议将不胜感激

当满足
stop()
的条件时,调用
stop()
,但代码继续,因此将请求新的rAF

只需在停止呼叫后添加一个返回以防止发生这种情况(或使用
else
):

。。。
如果(时间戳>=6000.0){
T.textContent=“停止!”;
stop();//stop()在这里只是一个子例程,调用后将继续

return;//看起来您需要调用
requestAnimationFrame(mainLoop)
无论如何,在
主循环的末尾
。是的……我的错……代码创建者也没有想到这一点?我也差点把我的脑袋都炸了。答案非常准确!谢谢!你能不能建议这个代码背后的基本框架适合创建游戏?我的代码至少是基于这个原则的。
//....

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