SetTimeout is often used to defer execution of a function, using the
SetTimeout (function () {
...
}, timeout);
SetTimeout (function...,0) is sometimes used for asynchronous processing, for example
function f () {
...//Get ready
SetTimeout (function () {
....//Do something
}, 0);
return ...;
}
function f is returned before the function processor set by settimeout;
When using asynchronous processing, especially when using the closure feature, be especially cautious;
for (var i = 0; i < i++) {
SetTimeout (function () {
Console.log (i);
}, 0);
}
For students who first use this method, it is likely that the program will print 0 ... 9, the results are indeed printed 10 10;
The problem is that when the loop is complete, the function is executed, and I has become 10,console.log (i) using 10!
Join your goal is to print 0 ... 9, then you can use the function parameter to save the 0....9 in a different way (actually using the closure)
for (var i = 0; i < i++) {
SetTimeout ((function (i){
return function () {
Console.log (i);
}
}) (i), 0);
}
Javascript setTimeout (0), closures