I am trying to understand two things about this code:
var updateFn = function(num){
return function(){
if(num == 6){
console.info("100%, all items saved!")
}
else{
var i = num/6;
var pct = Math.round(100 * i);
console.info(pct + "% saved");
}
};
};
for (var i = 1; i < 7; i++){
setTimeout(updateFn(i), i * 500);
}
-
According to what i have read about setTimeout() syntax;
setTimeout("javascriptstatement",milliseconds);So, why do I have to increment the milliseconds each loop till the total time until 500*6 ms?
Why doesn’tsetTimeout(updateFn(i), 500);work as intended? -
Why do I have to return a function for the function passed as the first parameter of
setTimeout?Why doesn’t this work?:
var updateFn = function(num){ if(num == 6){ console.info("100%, all items saved!") } else{ var i = num/6; var pct = Math.round(100 * i); console.info(pct + "% saved"); } }; for (var i = 1; i < 7; i++){ setTimeout("updateFn(i)", i * 500); }
Thanks in advance.
It seems it is setting 6 timeouts to occur every 500ms. I think
setIntervalmay be better here.You want to return a function because if you pass a string to
setTimeoutit getsevaled, and if you pass a function it just runs it.It seems this code is making a progress meter for a save operation, though assuming the save will take 3 seconds, and incrementing the counter every 1/2 second may not be the best idea.
Anyway, instead of setting 6 timeouts, it would be better to use
setInterval.