我在MDN上看到了一个例子,它使用requestAnimationFrame
而不是setTimeout
:
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/
var last_known_scroll_position = 0;
var ticking = false;
function doSomething(scroll_pos) {
// do something with the scroll position
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
}
ticking = true;
});
这让我想到了我们是否可以使用requestAnimationFrame
代替setTimeout(fn, 0)
,并且是否有任何优势?我已经谷歌搜索了一下,似乎所有比较都是在动画上下文中进行的,但是对于不相关的功能-如防抖节流或仅需要在重新绘制后运行代码的情况呢?