This is a test of my understanding of requestAnimationFrame . I need a debounce function, as I do some interaction with the DOM 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; spacing is usually the second argument. I assume that for a large number of user interfaces, the optimal interval is the shortest amount of time that does not overload the browser. It seems to me that exactly what requestAnimationFrame will 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 break from the debounce link above , but using requestAnimationFrame instead of setTimeout. In my opinion, this will suspend the transfer as soon as possible, but any calls arriving faster than the browser can handle will be dropped. This should ensure the greatest possible interaction. Am I on the right track? Or am I misunderstanding requestAnimationFrame ?
(Of course, this only works in modern browsers, but there are simple policies for requestAnimationFrame that simply return to setTimeout.)
javascript requestanimationframe debouncing
carpeliam
source share