简体   繁体   中英

setInterval() behaves differently in Firefox and Chrome

I wrote a function and wanted it to display 1 to 10 after every second in a span. While debugging the program I wanted to log the results to a console and saw different results for firefox and chrome, Chrome also changes the results ater every page refresh.

Below is my function:

function log10()  {
        for(var i =0;i<=10;i++)
        {
            console.log(setInterval(function() {
                $("span").text(i)
            },6000));
        }
}

FIREFOX RESULT LOGS: 2 to 11 (via firebug) and remains same on reload.

CHROME SHOWS: 1 to 11 (via built in debugger) And after every reload it shows 22 to 22 / 23 to 33 / 34 to 34 et-al

I am calling function via <body onload = log10();>

Does anyone know whats happening. I am more Interesting in knowing how to log 1 to 10 in span as per my code $("span").text(i)

You are not saving context, using an anonymous function for saving context. You should use setTimeout instead of setInterval , as setInterval will not stop until you stop it (using clearInterval or by unloading the page). At the other hand setTimeout will run only once for each loop with delay of 6000ms. jsfiddle

function log10()  {
    var i = 0;
    function repeat(){
        if(i > 10 ) return;
        setTimeout(repeat, 600);
        $("span").text(i);
        i++;
    } 
    repeat();
}

http://jsfiddle.net/8sdu5/2/

function log10()  {
    var counter = 1;
    var evt = setInterval(function() {
        $("span").text(counter++);
        if(counter > 10)
            clearInterval(evt);
    }, 1000);
}     

You don't need a loop, the setInterval will "loop" on its own, you just have to have a condition to tell it when to stop.

You are running into variable binding issues. A different way to solve them is to pass in the number to be shown combined with recursion and setTimeout:

Working jsFidle example

// recursive function
function log10(theNumber)  {
        if (theNumber <= 10)
        {
            setTimeout(function() {
                $("span").text(theNumber);
                log10(++theNumber);
            },1000);
        }
}

// kick things off
log10(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM