Reputation: 115
I have two code blocks here:
block1:
setTimeout(function(){
func1();
setTimeout(function(){
func2();
},500);
},500);
block2:
setTimeout(function(){
func1();
},500);
setTimeout(function(){
func2();
},1000);
What is the difference between these two blocks?(not only the results,but also the execution procedures)
Upvotes: 2
Views: 107
Reputation: 16019
In your comparison, the func2()
would be called a little bit later in the first block then in the second. Why? Because it first executes func1()
before triggering a new setTimeout()
timer.
// First scenario:
setTimeout()
*---------*----------*===*
500 1000
Func1()
*--*
setTimeout()
*-----------*
500
Func2()
*-*
// Second scenario:
setTimeout()
*---------*----------*
500 1000
Func1() Func2()
*-* *-*
The difference in most cases will be minimal. But it depends on what you do in func1()
. The execution time of that function will push the second timeout to a later point in time in respect to the first setTimeout()
.
On execution, timers and more of that stuff, I saw on jsConf in Berlin last year an interesting in-depth session about how the javascript engine works below the surface, in regard to the callstack, callbacks, asynchronous requests, etc. Those were 25 minutes well spend.
Philip Roberts: What the heck is the event loop anyway?
Upvotes: 2
Reputation: 700262
There are only subtle differences. On the whole you won't normally notice any difference.
In the first code block the second timer starts after func1
has run, so the timing will depend on how long that takes to run. The code blocks act more similar if you write block 1 like this:
setTimeout(function(){
setTimeout(function(){
func2();
},500);
func1();
},500);
However, there will still be a slight difference in timing. If the browser is busy running some code when a timer would be triggered, the execution of the callback would be delayed until that code completes. Any delay for the first timer would affect when the second timer starts.
Another difference is if you want to stop the timers. With block 1 the second timer depends on the first, so you can't stop them independently. Stopping the first timer will also stop the second, and the second timer can only be stopped after the first has completed.
With block 2 you can stop either timer independently at any time. The setTimeout
method returns a handle that is used if you want to stop it:
var handle1 = setTimeout(function(){
func1();
},500);
var handle2 = setTimeout(function(){
func2();
},1000);
Then later on you can use clearTimeout(handle1)
and clearTimeout(handle2)
to stop either timer.
Upvotes: 1