Javascript's setTimeout of USES the closure feature

  • 2020-03-30 03:59:46
  • OfStack

SetTimeout is often used to delay the execution of a function.


setTimeout(function(){
...
}, timeout);

SetTimeout (function...) is sometimes used for asynchronous processing. , 0); Such as:


function f(){
... // get ready
setTimeout(function(){
... . // do something
}, 0);
 
return ... ;
}

  Function f returns before setTimeout sets the function handler;

Be especially careful when using asynchronous processing, especially the closure feature.

Such as:


for(var i = 0 ; i < 10; i++){
setTimeout(function(){
console.log(i);
}, 0);
}

For those of you who are new to this approach, you might think that the program will print a 0... 9, the result does print 10 10;
The problem is that by the time the loop is complete, the function is executed, and the I has become 10. The console. Log (I) USES 10!
 
Add your purpose is to print 0... 9, then we can use the function parameter to save the 0... .9 (also using closures) :


for(var i = 0 ; i < 10; i++){
setTimeout((function(i){
return function(){
console.log(i);
}
})(i), 0);
}


Related articles: