Is it a good idea to use requestAnimationFrame in the debounce function?

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.)

+7
javascript requestanimationframe debouncing
source share
1 answer

That will work.

This has a caution that may or may not be important to you:

If the page is not currently visible, the animations on this page can be strangled so that they do not refresh frequently and, therefore, consume a small amount of processor power.

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

Otherwise, if you use this for animation, this is the intended use of requestAnimationFrame

+1
source share

All Articles