SetTimeout is often used to delay execution of a function:
Copy Code code as follows:
settimeout (function () {
...
}, timeout);
Sometimes the settimeout (function...,0) is used for asynchronous processing, for example:
Copy Code code as follows:
function f () {
..//Get Ready
settimeout (function () {
.../Do Something
}, 0);
return ...;
}
function f is returned before the function processor set by settimeout.
Be especially careful when using asynchronous processing, especially when using closure features;
For example:
Copy Code code as follows:
for (var i = 0; i < i++) {
settimeout (function () {
Console.log (i);
}, 0);
}
For the first time to use this method of students, it is likely that the program will print 0 ... 9, the result is actually printing 10 10;
The problem is that when the loop completes, the function is executed, and I has become 10,console.log (i) using 10!
Add your purpose is to print 0 ... 9, you can use the function parameter to save the 0....9 (in fact, the closure) in a different way:
Copy Code code as follows:
for (var i = 0; i < i++) {
SetTimeout ((function (i) {
return function () {
Console.log (i);
}
}) (i), 0);
}