Trouble Using Settimeout Function
Solution 1:
setTimeout
is not sleep
(JavaScript doesn't have a sleep
).
As you loop round, you set the function to run in 500ms, then you immediately set it to run again in 500ms, and so on. So effectively, you set it to run 100 times in 500ms, and have set i
to 100 before the first time it executes (since it takes a JS engine less then half a second to run that for loop 100 times).
You want something more like this:
var interval, i = 0;
interval = setInterval(function () {
if (i === 100) {
clearInterval(interval);
} else {
$("#progressbar").reportprogress(i);
i++;
}
}, 500);
Solution 2:
The issue is that variable i
becomes the part of the closure and, when the function is executed, is already equal to 100
.
The code you have currently literally creates a hundred of timeouts referencing the same variable(global i). By the time all of the functions are executed, i equals 100, therefore you report 100 as current progress 100 times.
The proper version should look like that:
functionrun() {
var i = 0;
setTimeout( functionupdateProgress() {
$("#progressbar").reportprogress(i++);
if (i < 100){
setTimeout(updateProgress, 500);
}
}, 500);
}
You could check closures part of javascript garden for explanation and possible other solutions.
Post a Comment for "Trouble Using Settimeout Function"