views:

118

answers:

1

I have this banner rotator code:

function ban_rot() {
    //First preload images
    // counter
    var i = 0;

    // create object
    imageObj = new Image();

    // set image list
    images = new Array();
    images[0] = "../Graphics/adv/1.gif"
    images[1] = "../Graphics/adv/2.jpg"

    // start preloading
    for (i = 0; i <= images.length; i++) {
        imageObj.src = images[i];
    }
    ///////////////////////
    var links = new Array("http://www.link1.com", "http://www.link2.se");
    var alts = new Array("alt1", "alt2");
    var titles = new Array("title1", "title2");

    var counter = 0;
    var banner_div = document.getElementById("ban_rot");
    cycle();

    function cycle() {
        if (counter == links.length) {
            counter = 0;
        }
        else if (counter < links.length) {
            banner_div.innerHTML = '<a href=\"' + links[counter] + '\"><img src=\"' + images[counter] + '\" border=\"1px\" style=\"border-color:#000;\" alt=\"' + alts[counter] + '\" title=\"' + titles[counter] + '\"></a>';
            //increase counter
            counter++;
        }
        setInterval(cycle, 8000);
    } //end cycle function
} //end ban_rot function

With this code, after around 2-3 minutes in Firefox or Chrome, the memory goes up and cpu goes to around 50%. The computer gets laggy and I have to terminate Chrome and FF.

Is there any reason for this in this code above?

Thanks

+16  A: 

Use setTimeout() instead of setInterval() here, like this:

setTimeout(cycle, 8000);

With setInterval() you're queuing more and more stacks of the function each time, rather than calling it once 8 seconds later, we're queueing another interval timer to run every 8 seconds, so you're getting this:

  • 8 seconds: 1 run
  • 16 seconds: 2 runs
  • 24 seconds: 4 runs
  • 32 seconds: 8 runs
  • ...uh oh

With setTimeout() you'll get just one run when the timer is up, not an additional run every 8 seconds.

To be clear, this happens because you're calling it each time it runs, with normal one-time usage this wouldn't be an issue, there's nothing inherently evil with setInterval().

Nick Craver
On first glance, this sounds a bit like there was a problem with `setInterval()` in general, but in fact the OP was just doing it wrong.
Tomalak
@Tomalak - you're right it does read that way, let me clarify a bit that it's specific to the usage.
Nick Craver