执行缓慢移动的脚本,设置超时未按预期工作



我正在编写一个脚本来在元素中创建缓慢运动,但它没有像我预期的那样执行。我正在使用settimeout来延迟操作,但现在它迭代超过 5steps的限制,我不确定为什么。感谢您的观看!

var step;
var steps = 5;
function init() {
step = 0;
}
function render() {
if (step < steps) {
console.log("yo!");
setTimeout(stepIncrease, 3000);
console.log("steps:");
console.log(steps);
}
requestAnimationFrame(render);
}
function stepIncrease() {
step++;
console.log("step:");
console.log(step);
}
init();
render();

您正在滥用 requestAnimationFrame 和 setTimeout。基本上,requestAnimationFrame在一秒钟内被调用60次。因此,在执行stepGrowth之前(3秒后(,函数render已经执行了几次setTimeout

。我不确定您要实现什么,但最简单的解决方案是将requestAnimationFrame移动到stepIncrease()函数内部。

var step;
var steps = 5;
function init() {
step = 0;
}
function render() {
if (step < steps) {
console.log("yo!");
setTimeout(stepIncrease, 3000);
console.log("steps:");
console.log(steps);
}
}
function stepIncrease() {
step++;
console.log("step:");
console.log(step);
requestAnimationFrame(render);
}
init();
render();

requestAnimationFrame()表示您请求窗口在下次重新绘制窗口之前运行该函数。setTimeout()将使用不同队列中的超时。

因此,由于您的渲染函数包含requestAnimationFrame(render);因此您基本上会告诉计算机:do this function on every frame。所以你基本上在这里创建了一个无限循环,setTimeout()ed函数永远不会运行以增加计步器。

var step;
var steps = 5;
function init() {
step = 0;
}
function render() {
console.log("steps:");
console.log(step);
if (step < steps) {
step++;
console.log("yo!");
setTimeout(render, 3000);
}
}
init();
render();

要延迟动作请求AnimationFrame,它应该是这样的

let step = 0;
let steps = 5;
const stepIncrease = () => {
step++;
requestAnimationFrame(render);
console.log("step:", step);
}
function render() {
if (step < steps) {
console.log("yo!");
setTimeout(stepIncrease, 3000);
console.log("steps:", steps);
}
}
render();

要了解实际发生了什么,请看这个演讲 事件循环到底是什么? |菲利普·罗伯茨 |JSConf

最新更新