为什么 cancelAnimationFrame 不起作用?
Why is cancelAnimationFrame not working?
参考这个fiddle - http://jsfiddle.net/rnqLfz14/28/
[此代码不是我的 - 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);
}
//...
cancelAnimationFrame 函数没有停止动画循环。有什么建议吗?我已经摸索了很长时间了,请提出任何建议,我们将不胜感激。
当满足 stop()
的条件时,将调用 stop()
但代码会继续,因此将请求新的 rAF。
只需在停止调用后添加 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
}
...
参考这个fiddle - http://jsfiddle.net/rnqLfz14/28/
[此代码不是我的 - 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);
}
//...
cancelAnimationFrame 函数没有停止动画循环。有什么建议吗?我已经摸索了很长时间了,请提出任何建议,我们将不胜感激。
当满足 stop()
的条件时,将调用 stop()
但代码会继续,因此将请求新的 rAF。
只需在停止调用后添加 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
}
...