I've come across this example on MDN that uses requestAnimationFrame
instead of 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;
});
And it got me thinking whether we can use requestAnimationFrame
instead of setTimeout(fn, 0)
and if there is any advantage to this? I've googled and it seems that all comparisons are done in the context of animations, but what about unrelated functionality - like debounce/throttle or simply if you need to run code after repaint?