Little help with JavaScript code involving setTimeout() method
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't
setTimeout(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
setInterval
may be better here.You want to return a function because if you pass a string to
setTimeout
it getseval
ed, 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
.
var updateFn = function(num){
if(num == 6){
console.info("100%, all items saved!");
clearInterval(saving);
}
else{
var i = num/6;
var pct = Math.round(100 * i);
console.info(pct + "% saved");
}
};
var count = 1
var saving = setInterval(function(){
updateFn(count++);
}, 500);
setTimeout(updateFn(i), 500);
works as intended but probably not the way you'd hope it to work.
You are basically creating 6 timeouts which are executed at the exact same time (500 ms from now).
If you want them to be created 500ms apart from each other, then setTimeout(updateFn(i), i * 500);
is the correct way to do it (or put setTimeout(updateFn(i), 500);
inside of the updateFn
function). If you want them to occur every 500ms you could also use setInterval
.
For 1: there is no reason (edit: no, there is: it postpones on execution 500ms after the other. As someone noted, setInterval is the way to go there), apparently: maybe the writer needs a way to simulate some "slowing down" effect in the fake saving function.
For 2: for setTimeout to work, you have NOT to return a function, but you DO have to for how that code is written: the first parameter of setTimeout is some code to be executed, and is quite standard to pass setTimeout a function (like an anonymous one). As in:
setTimeout(function() {
console.log("Hello world, 2 sec in the future");
}, 2000)
精彩评论