console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');
The output is: 'one' 'three' 'two'
What happens behind the scene? Why the code produces this output?
console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');
The output is: 'one' 'three' 'two'
What happens behind the scene? Why the code produces this output?
setTimeout()
don`t execute the given function "In X seconds after that you declare it", Behind the scenes, this method puts the given function in a stack that will be executed 'X second after that the code in the execution context have been executed, in this case, when the line 1 and the line 4 of your code has been executed"
An example
setTimeout(function() {
console.log('four');
}, 10);
console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');
//Output: 'one', 'three', 'two', 'four'
Behind the scenes:
In the execution context
console.log('one');
console.log('three');
after the execution context
setTimeout(fn, ms)
sort in order of the second parameter, in milliseconds:
console.log('two');//0 ms after the execution context has been executed.
console.log('four'); //10ms after the execution context has been executed
EDIT: Have been search the link that in the next response explains graphically how works the javascript-browser queue, check it out!
The javascript interpreter runs all code single-threaded in a big event loop; your calling setTimeout
enqueues the callback as another event to be executed as soon as the current code is done (and other code that may have been enqueued previously).
So the interpreter executes it like this:
get and execute next event
calling your global <script> code
calling console.log('one');
calling setTimeout(func);
calling console.log('three');
returning from your global <script> code
get and execute next event*
calling setTimeout callback
calling console.log('two');
returning from setTimeout callback
(*): There may be other callbacks enqueued to be called between these two.
Javascript uses event loop to execute asynchronous code. Javascript is single threaded so all the callbacks is run one by one using callback queue. Code runs in a series of "ticks". This means that the queue processing only happen when the previous one is finished. Here setTimeout registers a callback and returns. There are next lines of code to be executed so they will execute first in this call stack. After there are nothing to be executed only then the registered callback will get executed.
A visual explanation is given here: http://latentflip.com/loupe/?code=Y29uc29sZS5sb2coJ29uZScpOwpzZXRUaW1lb3V0KGZ1bmN0aW9uKCkgewogIGNvbnNvbGUubG9nKCd0d28nKTsKfSwgMCk7CmNvbnNvbGUubG9nKCd0aHJlZScpOw%3D%3D!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D