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, you can refer to setTimeout which is often used to delay the execution of a function. Its usage is as follows:
The Code is as follows:
SetTimeout (function (){
...
}, Timeout );
Sometimes setTimeout (function ..., 0); for example:
The Code is as follows:
Function f (){
... // Get ready
SetTimeout (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 );
}