setTimeout is often used to delay execution of a function, and is used as:
The code copy is as follows:
setTimeout(function(){
…
}, timeout);
Sometimes, setTimeout(function…,0) is used for asynchronous processing; for example:
The code copy is as follows:
function f(){
… // get ready
setTimeout(function(){
…. // do something
}, 0);
return …;
}
Before the function processor set by setTimeout, function f returns;
Be especially careful when using asynchronous processing, especially when using closure features;
For example:
The code copy is as follows:
for(var i = 0 ; i < 10; i++){
setTimeout(function(){
console.log(i);
}, 0);
}
For students who use this method for the first time, they are likely to think that the program will print 0…9, but the result is that 10 are indeed printed 10;
The problem is that when the loop is completed, the function is executed, and i has become 10, and 10 is used in console.log(i)!
The purpose of adding you is to print 0…9, so you can change the method and use function parameters to save 0….9 (actually, it also uses closures):
The code copy is as follows:
for(var i = 0 ; i < 10; i++){
setTimeout((function(i){
return function(){
console.log(i);
}
})(i), 0);
}