SetTimeout are often used to delay the running of a function, using the method of
SetTimeout (function () {
...
}, timeout);
Sometimes settimeout (function...,0) is 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 you are using asynchronous processing. Especially when using the closure feature. be particularly careful;
for (var i = 0; i < i++) {
SetTimeout (function () {
Console.log (i);
}, 0);
}
For the first time to use such a way of students. It is very 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 gets run, and I has become 10,console.log (i) using 10!
Increase your aim is to print 0 ... 9, it is possible to use a function reference to save the 0....9 in a different way (actually using closures)
for (var i = 0; i < i++) {
SetTimeout ((function (i){
return function () {
Console.log (i);
}
}) (i), 0);
}
Javascript setTimeout (0), closures