When is the function registered with setTimeout called?
it maybe called after 'some' normal c开发者_StackOverflow中文版ode is executed? but i not sure... it would be great if some one kind enough to depict a big picture of how javascript code is executed in a browser.
For most of the time the browser execution thread is idle, not running any code. When you register some function to be executed using setTimeout
, it will be executed not earlier than after given amount of milliseconds.
Now: if after given amount of time some other code is executing (like event handler or a long loop), browser worker thread is busy and your function will have to wait. Consider this code:
setTimeout(f, 500);
for(var i = 0; i < 10000000; ++i){
//...
}
setTimeout
returns immediately allowing the execution of the loop. If this loop runs for more than 500 milliseconds, it won't be interrupted and your f
function will have to wait. The same thing will occur if after e.g. 490 milliseconds you trigger some lengthy event handler.
Consider browser JS worker thread as a queue with a single consumer and multiple producers. Some items in the queue can be picked up immediately (like event handlers), some have to wait until their timeout expires.
Javascript is single threaded and runs with a callstack, which is essentially first come first serve processing.
The setInterval and setTimeout functions put the passed function into the callstack after the supplied duration has elapsed. The distinction here is that the results are not executed at that time, they're simply put into the callstack, so if something is already running, it won't execute your function supplied in the timeout until you're finished.
For example:
var i = 0;
setTimeout(function() { i = 1; }, 10);
for (; i < 1;) {}
You'll never get out of that for loop, even though after 10ms, the function to set i to 1 is called, it's only on the callstack, and won't take affect until the for loop is done.
Maybe Im not understanding the question.. but this is taken directly from the window
spec.
setTimeout(function, milliseconds) This method calls the function once after a specified number of milliseconds elapses, until canceled by a call to clearTimeout. The methods returns a timerID which may be used in a subsequent call to clearTimeout to cancel the interval.
Reference
Basically the function is called right after the amount of milliseconds you specified has passed.
精彩评论