Reputation: 8430
I am using setTimeout function:-
function myFunction() {
alert("1"); // Called 1st
setTimeout(function(){
alert("2"); // Called Third
}, 0000);
/*Same as setTimeout window.setTimeout(slowAlert, 0000);function slowAlert() { alert("That was Same as setTimeout!");}*/
alert("39"); // Called Second
}
I am unable to understand why alert('2') calls on third time even I am using zero seconds
Upvotes: 0
Views: 1162
Reputation: 105489
setTimeout
adds your callback to the event loop, which will be called later when a browser isn't busy. The second parameter just tells a browser when your callback will be added to the event loop, not when execute it. In your case it's zero, so the callback is added almost immediately (it's actually in about 4 milliseconds) to the loop, but it will be executed later when a browser has time. The other alerts in your code don't use setTimeout
and so they are executed immediately in current tick, that's why they are executed before the callback.
Upvotes: 3
Reputation: 5262
setTimeout()
calls callback function asynchronously. So there is no guarantee of order even though it is set with zero timeout.
To make it synchronous, remove setTimeout()
and just call alert('2');
directly.
function myFunction() {
alert("1"); // Called 1st
alert("2"); // Called second
alert("39"); // Called third
}
Update:
If you want to make sure that the order remain intact then move alert("39")
also inside setTimeout()
.
function myFunction() {
alert("1"); // Called 1st
setTimeout(function() {
alert("2"); // Called second
alert("39"); // Called third
}, 0);
}
Upvotes: 1
Reputation: 7107
Because setTimeout is asynchronous kind of function. Because it breaks the synchronous execution flow. But it does not executed simultaneously like a separate thread.
setTimeout(function(){
alert("2"); // Called Third
}, 0000);
The above code executed once after all other statements outside of it are finished executing.
Upvotes: 0
Reputation: 12389
Ok, so, let's work a tick at a time and see what your app is doing :
Tick 1 - alert("1"); An alert, better display it now!
Tick 2 - setTimeout(function(){ },0000); A timeout with 0seconds? OK, I'll wait
Tick 3 - alert("39"); Another Alert, display!!
Tick 4 - alert("2"); It's been 0 seconds, what was in that timeout again?
Upvotes: 1
Reputation: 379
since JS in browser is single threaded setTimeout creates a new "stack" that gets executed n
milliseconds after the current stack is cleared, i.e. after the current function finished
Upvotes: 0