The fourth edition of the JavaScript authoritative guide says "Window object method settimeout () is used to schedule a JavaScript snippet to run at a specified time in the future."
SetTimeout (Foo,i); Foo is the callback function, I is the delay time
Note that the word "future", SetTime will put the Foo function in the queue, when the thread is idle, JavaScript will execute the event in the queue.
Look at the following code:
<!DOCTYPE HTML><HTML> <Head> <Scripttype= "Text/javascript">window.onload= function () { vara= 0; functionOne () { for (varI= 0; I< Ten; I++) {console.log (i); SetTimeout (function() {console.log (a); A+=i; },0); }; } functionBoth () {alert (a); } one (); SetTimeout (both,0); } </Script> </Head></HTML>
In fact, the one function looks like it will normally add a from 0 to 9, then alert out.
But the actual alert result is , why?
The For loop of the one function does not stop because it settimeout, and when it encounters settimeout, it simply puts the callback function inside the queue and continues to i++. Wait until all the for loops are executed to execute the function just put into the queue. Because the loop is over, I is 10, with a total of 10 identical a+=i, the function of the operation is called, and the result of a finally becomes 100.
But in fact the above code Part I still do not understand, is if settimeout (two,0), change to settimeout (0), then the result of alert becomes 0.
The first parameter of settimeout is the function object, and if it becomes two (), the callback function becomes the return value of two.
The settimeout of JavaScript learning