Slideshow / Clearing All Javascript Timers
I decided to whip up a slideshow for the photo albums, since a few people have asked for it. First I thought about finding a flash one, but I knew that it would probably ask for a simple directory of images, and doodlekit doesn't store images that way. So I figured I could just use Ajax and some Scriptaculous effects instead. The end result is pretty slick
One thing I had to do to make it look so good is preload the next image, so you can't see it loading when the last one is fading. To do this I have a temporary div that sits over the main image div. I copy image A into the temp div, load image B in the main div, then fade the temp div. This requires me to use four different timers for various purposes to make everything look smooth.
However, I ran into a problem when I added the previous and next links. When you clicked on either, it loaded the proper image fine but the timers where still running. This started a chain reaction of all kinds of crap.
I needed a way to stop the timers, but I was using Rail's Javascript helpers which meant I couldn't just get the timer's id and call clearTimeout.
Instead I came up with a cool way to clear all the timers in one swoop. Basically I override the setTimeout method and store each timer id in an array. Then when I need to I just loop through the array and clear them all.
timers = new Array();
oldSetTimeout = window.setTimeout;
window.setTimeout = function(code, interval) {
timers.push(oldSetTimeout(code, interval));
}
function resetTimeouts() {
timers = new Array();
}
function clearTimeouts() {
for (var i= 0;i < timers.length; i++) {
clearTimeout(timers[i]);
}
resetTimeouts();
}
I know this isn't totally elegant, but I think it's a good solution to a sticky problem. To use, just include this code and call clearTimeouts whenever you want. I extracted resetTimeouts so it could be called after each slide transition, and so the timer array didn't just keep growing.




Post a Comment