Reputation: 3418
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)
Upvotes: 2
Views: 4628
Reputation: 23208
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();
}
Upvotes: 3
Reputation: 57715
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:
// recursive function
function log10(theNumber) {
if (theNumber <= 10)
{
setTimeout(function() {
$("span").text(theNumber);
log10(++theNumber);
},1000);
}
}
// kick things off
log10(0);
Upvotes: 0
Reputation: 21106
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.
Upvotes: 3