Search code examples
javascriptscrollrequestanimationframecancelanimationframe

Is there an optimization in canceling request animation frame?


Would there be any benefit(or even possible in window.cancelAnimationFrame(); this example below?

If so, How would I do so, and why?

Ref: requestAnimationFrame MDN

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;
});

Solution

  • You could avoid the anonymous function by passing directly doSomething as the rAF parameter and by including the ticking = false directly in doSomething.

    You can also remove the last_known_scroll_position variable declaration since it's just window.scrollY, which also removes the need to have a parameter to doSomething. By the way, it's better to use pageYOffset than scrollY, for wider browser support.

    Otherwise, your logic is the good one.

    This flag will avoid stacking an other function call when one is already waiting, and the use of cancelAnimationFrame would have just unecessarely filled your memory with the creation of this anonymous function, forcing a premature GC kick.

    So once everything is applied, you've got something like :

    var ticking = false;
    
    function doSomething() {
      ticking = false;
      var scroll_pos = window.pageYOffset;
      // do something with the scroll position
    
    }
    
    window.addEventListener('scroll', function(e) {
      if (!ticking) {
        window.requestAnimationFrame(doSomething);
      }
      ticking = true;
    });