jquery-resize icon indicating copy to clipboard operation
jquery-resize copied to clipboard

RequestAnimationFrame instead of setTimeOut

Open Zae opened this issue 13 years ago • 6 comments

I've implemented requestAnimationFrame instead of setTimeOut, should be a bit more efficient.

It uses a fallback to setTimeOut if the browser does not support requestAnimationFrame.

I also used the Google Closure Compiler to create the minified version.*

Zae avatar Nov 10 '11 00:11 Zae

What's the benefit to using requestAnimationFrame for non-animation tasks?

cowboy avatar Nov 10 '11 02:11 cowboy

Mostly the standard benefits of requestAnimationFrame.

Hopefully the resize will be detected in the same frame as the resize actually happens, causing less delay between the resize and the event being triggered and better synchronizing the event with CSS Transformations and animations.

Also requestAnimationFrame uses a smart way of measuring the time before starting the next. This way there is no set delay between polling but the browser calculates the best time when to update. This way the browser will automatically throttle the updates when the hardware is underpowered or for example the tab is not active.

The drawbacks of this method are that the browser chooses how often the event is fired and not the standard delay you set. Also it might cause more redraws than needed. The redraw problem could be fixed by giving the requestAnimationFrame function the context where the resize will be happening. But the single event loop design would need to be changed for that.

Giving context to requestAnimationFrame could also lead to better optimization for example when the element is scrolled out of view.

Zae avatar Nov 10 '11 09:11 Zae

In your solution, when using requestAnimationFrame, how would you clear a timeout?

cowboy avatar Nov 10 '11 13:11 cowboy

Hmm, did not think about that.

There is a clearTimeOut() version for requestAnimationFrame tho.

I'll look at it tonight and update the patch.

Zae avatar Nov 10 '11 13:11 Zae

Had to add some code to make sure the loop is cancelled.

Firefox doesn't implement cancelAnimationRequest yet. This also makes sure the loop is cancelled if the clear method is called while the code in the loop is running.

Zae avatar Nov 12 '11 14:11 Zae

Has this been implemented? If not, has a reason been given?

Spotnyk avatar Aug 23 '12 15:08 Spotnyk