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.)
var obj = this
. That way people will not have to usebind
before calling and saves creating one more function scope – Tensive