Garbage Burrito

Slideshow / Clearing All Javascript Timers

Slideshow / Clearing All Javascript Timers
Ben Kittrell - 05/31/2007 16:07:00
Comments: 4
Last Comment: 07/02/2007 21:27:43

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.

Comments: 4
Last Comment: 07/02/2007 21:27:43

Comments

1. Stephen Ausman   |   06/05/2007 00:58:10

Slideshow feature is awesome :)

Can't wait to see what you make next.

2. rheaghen   |   06/11/2007 12:08:46

pretty slick ben. =)

3. rheaghen   |   07/02/2007 19:45:14

Hey, it would also be pretty cool if the next, previous links also used the fade effect.

4. Ben Kittrell   |   07/02/2007 21:27:43

Yeah, I wanted to, but the timing is already pretty complicated and volatile. I might try that later.

Post a Comment


Are you human? Please enter the word below.
M2zhcmnllmpwzzeynju2mtc1ntk=


powered by Doodlekit™ Free Website Builder by Doodlebit™ Website Company