Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use requestAnimationFrame within a debounce function?

This is a check on my understanding of requestAnimationFrame. I have a need for a debounce function, as I'm doing some DOM interaction every time the window is resized and I don't want to overload the browser. A typical debounce function will only call the passed function once per interval; the interval is usually the second argument. I'm assuming that for a lot of UI work, the optimum interval is the shortest amount of time that doesn't overload the browser. It seems to me that that's exactly what requestAnimationFrame would do:

var debounce = function (func, execAsap) {
   var timeout;

  return function debounced () {
    var obj = this, args = arguments;
    function delayed () {
      if (!execAsap)
        func.apply(obj, args);
      timeout = null; 
    };

    if (timeout)
      cancelAnimationFrame(timeout);
    else if (execAsap)
      func.apply(obj, args);

    timeout = requestAnimationFrame(delayed); 
  };
}

The above code is a direct rip-off from the above debounce link, but with requestAnimationFrame used instead of setTimeout. In my understanding, this will queue up the passed-in function as soon as possible, but any calls coming in faster than the browser can handle will get dropped. This should produce the smoothest possible interaction. Am I on the right track? Or am I misunderstanding requestAnimationFrame?

(Of course this only works on modern browsers, but there are easy polyfills for requestAnimationFrame that just fall back to setTimeout.)

like image 370
carpeliam Avatar asked Mar 31 '15 01:03

carpeliam


1 Answers

This will work.

It has a caveat that may or may not be important to you:

If the page is not currently visible, animations on that page can be throttled heavily so that they do not update often and thus consume little CPU power.

So if you for some reason care about this for the function you are debouncing, you are better off using setTimeout(fn, 0)

Otherwise if you are using this for animations, this is the intended usage of requestAnimationFrame

like image 168
mkoryak Avatar answered Oct 06 '22 06:10

mkoryak