title: Is it a good idea to use requestAnimationFrame within a debounce function?
body: <p>This is a check on my understanding of <code>requestAnimationFrame</code>. I have a need for a <a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">debounce</a> 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 <code>requestAnimationFrame</code> would do:</p>
  
  <pre><code>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); 
    };
  }
  </code></pre>
  
  <p>The above code is a direct rip-off from <a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">the above <code>debounce</code> link</a>, 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 <code>requestAnimationFrame</code>?</p>
  
  <p>(Of course this only works on modern browsers, but there are easy polyfills for requestAnimationFrame that just fall back to setTimeout.)</p>