There are so many questions about JavaScript's requestAnimationFrame already and (I think) I understand the concept but is there any performance difference between with and without cancelAnimationFrame in this context?
// Setup a timer
var timeout;
// Listen for resize events
window.addEventListener('scroll', function () {
console.log( 'no debounce' );
// Cancel last animation, if there's one
if (timeout) {
window.cancelAnimationFrame(timeout);
}
// Setup the new requestAnimationFrame()
timeout = window.requestAnimationFrame(function () {
// Run our scroll functions
console.log( 'debounced' );
});
}, false);
without cancelAnimationFrame:
// Setup a timer
var timeout;
// Listen for resize events
window.addEventListener('scroll', function () {
console.log( 'no debounce' );
// Setup the new requestAnimationFrame()
window.requestAnimationFrame(function () {
// Run our scroll functions
console.log( 'debounced' );
});
}, false);
I get the same result on each code.
But I want to know what happens if I don't cancel the animation frame. Does requested function get stacked somewhere in memory or something?
If we schedule a continuous separate
requestAnimationFrameloop while wescroll, we will clearly see thatrAFandscrollcallbacks are happening at max once per VSync event.Thus returning to your main question
Generally no, because your
requestAnimationFrame()call is blocking the nextscrollcallback, and you cannot have more scroll callbacks executed than your requested frame callback, there is a 1 to 1 correlation, since they both happen at max every frame render.All requested animation frame callbacks are stacked in the internal pool of callbacks, that get flushed before the nearest Vsync event. So yes technically the only way to remove the scheduled callbacks is
cancelAnimationFrame(), but again it's not relevant in your case since yourrequestAnimationFrame()callback is happening at the "same" time with windowscrollcallback.Hope it makes sense.