This article mainly introduces the things you need to pay attention to when using the closure feature of setTimeout (0) in Javascript. If you need it, refer to the next article to introduce the setTimeout (0) in Javascript) when using the closure feature, you need to pay attention to the following issues. For more information, see
SetTimeout is often used to delay the execution of a function. Its usage is:
The Code is as follows:
setTimeout(function(){…}, timeout);
Sometimes setTimeout (function ..., 0); for example:
The Code is as follows:
function f(){… // get readysetTimeout(function(){…. // do something}, 0); return …;}
Function f returns the result before the function processor set by setTimeout;
Be especially careful when using asynchronous processing, especially the closure feature;
For example:
The Code is as follows:
for(var i = 0 ; i < 10; i++){setTimeout(function(){console.log(i);}, 0);}
For those who use this method for the first time, they may think that the program will print 0... 9. You can print 10 10 results;
The problem is that when the loop is completed, the function is executed, and I has changed to 10, and 10 is used in console. log (I!
Add to you to print 0... 9, you can use the function parameter to save 0 .... 9 (actually, the closure is used ):
The Code is as follows:
for(var i = 0 ; i < 10; i++){setTimeout((function(i){return function(){console.log(i);}})(i), 0);}
For more information about the closure feature of setTimeout () in Javascript, see the PHP Chinese website!