Reputation:
I have the following code, I am trying to simply count to ten using a FOR loop
Through each iteration I want to use jQuery
to update a div element with the value of i
for (i=0;i<=10;i++){
setTimeout(function(){
$(".test").html(i);
},10000);
}
The problem is, the loop will execute and not display anything until finished, which will simply be the number 10.
Is there a way to achieve what I need?
Thank
Upvotes: 1
Views: 6246
Reputation: 206514
var i = 0,
T =setInterval(function(){
i < 10 ? $(".test").html(++i) : clearInterval(T);
},1000);
$(".test").html(i);
Upvotes: 2
Reputation: 101533
Try using setInterval()
instead:
var i = 0;
var timer = setInterval(function() {
$('.test').html(i);
i++;
if(i > 10) {
clearInterval(timer);
}
}, 10000);
Your current loop will loop as fast as it can, and set 10 timeouts to occur in approximately 10 seconds after the loop is called. What setInterval()
does is call the code in the function passed to it every 10 seconds, in effect delaying the loop.
The if()
statement at the end of it stops the interval occurring if i > 10
by clearing the variable the interval was given a reference to.
I've forked your JSFiddle here, with a 100ms wait time instead of 10s for testing purposes.
Upvotes: 1
Reputation: 255065
Your code doesn't work as expected because of closure effect. It is usually solved by creating another anonymous function that is called right after it is created:
for (i=0;i <= 10;i++){
(function(i) {
setTimeout(function(){
$(".test").html(i);
}, i * 1000);
})(i);
}
http://jsfiddle.net/zerkms/GgzFW/4/
Upvotes: 7