jQuery 1.6.1+ and setInterval

I recently created a quick jQuery gallery plugin for a client that auto scrolls using setInterval and, when I was done, I left my tab hidden for a few minutes to look at something on another website.  When I went back to my tab with the gallery, WHAM! I was stuck with a gallery automatically scrolling in rapid section, all crazy and nonsensical.  I knew that jQuery 1.6.1 is now using the more efficient requestAnimationFrame to animate the transitions, but this behavior was totally unexpected.

I looked into the fadeIn documentation and found this little surprise.

Because of the nature of requestAnimationFrame(), you should never queue animations using a setInterval or setTimeout loop.

Okay then.

The documentation suggests using the animation callbacks or the jQuery .queue() function on the element I’m fading in, but that wouldn’t really work with my gallery set up because I wanted to stop the automatic scrolling when a user interacts with the gallery. I didn’t want to mess with booleans to do the behavior, especially since everything was working how I wanted it to already.

I did a little research and found these nice shims from Paul Irish and Joe Lambert that you can use in place of setInterval, clearInterval, setTimeout, and clearTimeout.

https://gist.github.com/1043569.

To use them, you have to include the first shim for requestAnimFrame from Mr. Irish, then include the shims for (set/clear)Interval and/or (set/clear)Timeout.  In my case, I just needed the ones for setInterval and clearInterval.  Then, where you were calling setInterval(func, poll), you now call requestInterval(func, poll).  Where you call clearInterval(interval), you now call clearRequestInterval(interval);

Hope that helps you out!

Comments

    Dennis |

    Thank you very much for sharing this, it was very helpful for me – I experienced exactly the same problem and using requestInterval and clearRequestInterval worked well :)

    Jonathan Pacheco |

    +1 on the thanks, this issue had been bothering me for a bit and this is a nice fix for plugins already dependent on setInterval, etc. Thanks for sharing the find.

    Caleb |

    Of course. Glad it helped somebody!

    Antonds |

    Thank you for this post, very helpful.

    Caleb |

    Apparently they had so many problems with this that they have decided to remove the requestAnimFrame integration in jQuery 1.6.3. If you’re experiencing issues with this, I suggest you use that version or better instead.