« Back to blog

jQuery Animation Queue Fix

I've recently found an interesting bug/nuance when using jQuery animations with Javascript timing (setTimer/setInterval) in Firefox/Chrome.

Basically Firefox and Chrome try to be clever and, instead of continuously playing a repeating animation (like our carousels) whilst the window is not active, it saves processor usage by "pausing" the animation in a queue. The only downside is that the queue is then dumped out in full when the window is active again, meaning it will cycle through the stored animation in matter of seconds, which doesn't look good.

There are a number of documented fixes, including the jQuery.queue() function and Mozilla's own window.mozRequestAnimationFrame(), but I didn't have any luck incorporating these into our existing code.

The fix I finally got to was using window.onblur and window.onfocus to find if the window containing the animation is active or not. The following code is something I've recently implemented:

window.onblur = function () { $('#div').stop(); clearTimeout(timer); console.log("blur"); };

window.onfocus = function () { clearTimeout(timer); startTimer(); console.log("focus"); };

This simply stops the animation and clears the timer if the window loses focus, then clears the timer and restarts the timer when it regains focus. Simple, ja?

Worth noting if you're putting in any timed Javascript animations.

Comments (1)

Nov 21, 2011
Erich said...
Saved my life. :P Thanks bro.

Leave a comment...