使用 requestAnimationFrame 的错误行为
Buggy behavior using requestAnimationFrame
我写了一个有用的库来绘制和动画 SVG 路径的笔划:segment。你可以 check it on github.
前段时间我用 requestAnimationFrame
替换(接受合并请求)setTimeout
调用,以加快现代浏览器中的动画速度,同时也使用提供的 polyfill作者:Paul Irish。
现在,当我尝试以非常低的延迟为多个 paths
设置动画时,我正在尝试使用 requestAnimationFrame
调用进行错误行为。
我准备了 2 个演示来展示 setTimeout
(正常工作)和 requestAnimationFrame
(错误行为)的行为。请检查:
在 requestAnimationFrame
演示中,我修改了一些我的库以在控制台中打印一些有用的信息,您可以在其中看到错误行为:
(function calc(){
// Checking if it's the first element, the buggy behavior happens in the firsts elements
if(that.class === 'first'){
console.log('calc');
}
// Some code here that can break the recursive loop and stop execution of calc function
if(that.class === 'first'){
console.log('calc call');
}
that.timer = window.requestAnimationFrame(calc);
// More code here
})();
根据前面的代码,在每条 'calc call' 消息之后应该出现一条 'calc' 消息。但这不是我能看到的,至少在 Firefox 和 Chrome 中是这样。这是大多数时候的控制台输出:
calc
calc call
calc
calc call
我真的不知道发生了什么,所以欢迎任何帮助:)
这里的错误行为是因为 timeoutID
和 return 来自 requestAnimationFrame
的值被保存到同一个变量中。将它们保存在不同的变量中将解决问题。
这是一个codepen
我写了一个有用的库来绘制和动画 SVG 路径的笔划:segment。你可以 check it on github.
前段时间我用 requestAnimationFrame
替换(接受合并请求)setTimeout
调用,以加快现代浏览器中的动画速度,同时也使用提供的 polyfill作者:Paul Irish。
现在,当我尝试以非常低的延迟为多个 paths
设置动画时,我正在尝试使用 requestAnimationFrame
调用进行错误行为。
我准备了 2 个演示来展示 setTimeout
(正常工作)和 requestAnimationFrame
(错误行为)的行为。请检查:
在 requestAnimationFrame
演示中,我修改了一些我的库以在控制台中打印一些有用的信息,您可以在其中看到错误行为:
(function calc(){
// Checking if it's the first element, the buggy behavior happens in the firsts elements
if(that.class === 'first'){
console.log('calc');
}
// Some code here that can break the recursive loop and stop execution of calc function
if(that.class === 'first'){
console.log('calc call');
}
that.timer = window.requestAnimationFrame(calc);
// More code here
})();
根据前面的代码,在每条 'calc call' 消息之后应该出现一条 'calc' 消息。但这不是我能看到的,至少在 Firefox 和 Chrome 中是这样。这是大多数时候的控制台输出:
calc
calc call
calc
calc call
我真的不知道发生了什么,所以欢迎任何帮助:)
这里的错误行为是因为 timeoutID
和 return 来自 requestAnimationFrame
的值被保存到同一个变量中。将它们保存在不同的变量中将解决问题。
这是一个codepen