开发者

Why is this javascript code making browser draw 50% CPU and so much memory?

开发者 https://www.devze.com 2023-01-22 14:06 出处:网络
I have this banner rotator code: function ban_rot() { //First preload images // counter var i = 0; // create object

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>';
       开发者_JS百科     //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


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().

0

精彩评论

暂无评论...
验证码 换一张
取 消