Reputation: 2160
I have a for loop that is supposed to update a div with a counter.
The code looks like this:
for(var i=0; i < $this.files.length; i++) {
var update = setInterval(function() {
$(".counter").html('<p>Processing file ' + (i+1) + ' of ' + $this.files.length + '.</p>')
},1000);
//do other stuff
}
However it does not update.
What am I doing wrong?
Upvotes: 0
Views: 168
Reputation: 3467
It will not work, simply because you are looping trough with i VERY quickly and set up several timers which will expire VERY soon after each other, meaning for the human eye only the last value will be visible, therefore you need to make a loop function with timer to achive the desired result something like this:
function update_progress(cur, max){
setTimeout(function() {
$(".counter").html('<p>Processing file ' + cur + ' of ' +max + '.</p>');
if (cur<max) {cur++; update_progress(cur,max);}
},1000);
//do other stuff
}
update_progress(1, $this.files.length);
I hope you see the flaw in your process now, and I hope this helps you. Emil
Upvotes: 0
Reputation: 16785
The problem is that while looping, you just define $this.files.length
different intervals that will work every second forever.
Try this instead:
var len = $this.files.length;
var i = 0;
var update = setInterval(function() {
$(".counter").html('<p>Processing file ' + (i+1) + ' of ' + len + '.</p>');
if (++i == len) clearInterval(update);
},1000);
Upvotes: 2