setTimeout without arguments 1

setTimeout without arguments

/*
setTimeout removes the function from the execution queue and it will only be invoked after JavaScript has finished with the current execution queue. 
*/

console.log(1);
setTimeout(function() {console.log(2)});
console.log(3);
console.log(4);
console.log(5);
//console logs 1,3,4,5,2

Here is what the above code is Doing:
1. The first console.log(1) is executed.
2. The setTimeout function is invoked. The function passed to setTimeout is added to the callback queue.
3. The next console.log(3) is executed.
4. The next console.log(4) is executed.
5. The next console.log(5) is executed.
6. The JavaScript engine has finished executing the current execution queue.
7. The function passed to setTimeout is removed from the callback queue and added to the execution queue.
8. The function passed to setTimeout is executed.

Similar Posts