All about setTimeout() in java script

All about setTimeout() in java script

Let's not set time out for learning setTimeout(). Let's learn it now.

The setTimeout() method executes a block of code after the specified time.

The commonly used syntax of JavaScript setTimeout is:

setTimeout(function, delay);

Its parameters are:

  • function - a function containing a block of code we want to execute

  • delay - the time after which we want to execute a function in milliseconds

Let's say we have code like this:-

console.log("hello");

setTimeout(function(){
    console.log("world!")
},1000);

console.log("in javascript");

what do you think will be output..?

  1. It will print hello first, then wait for 1000ms and after that, it will print world! and then print javascript.

  2. It will print hello first then javascript and then world!

If your answer is 2 you are correct but the question is why..? We know that javascript is a synchronous single-threaded language which means it can perform one task at a time and it will wait till the task gets completed before executing the next one.

Then why it prints "in javascript" before "world"..?Let's find out.

setTimeout() is not part of core javascript but it is part of the browser's web APIs and is asynchronous.

what happens is when we encounter setTimeout() it will register function in Web APIs and also create a timer in the Web APIs and javascript will continue executing whatever next is there in the call stack.

when the timer expires that function will be pushed into the callback queue component of the browser.

The event loop will continuously monitor both call stack and callback queue when the call stack becomes empty the event loop removes the function from the callback queue, places it on the call stack, and executes it.

Now I hope you understand why the answer is option 2. The important thing to note here is a function from the callback queue will be pushed into the call stack only when the call stack becomes empty. Let's take one example to understand it.

setTimeout(function(){
    console.log("world!")
},1000); //timer for 1000ms 
let currentTime=new Date().getTime();
const endTime=currentTime+5000;
while(currentTime<=endTime) //loop will run for 5000 ms
{
    currentTime=new Date().getTime();
}
console.log("hello");

If you think that world! will be printed after 1000ms and then it will print hello then you are wrong. what happens is after 1000ms our function will be pushed in the callback queue but the call stack is not because we are still running global code so the event loop will not push anything from the callback queue into the call stack. when we finish executing console.log("hello") our call stack will be empty and then the function from the callback queue will be pushed into the call stack and will be executed.

So setTimeout() with the delay of t seconds means callback function will be executed at least after t seconds it doesn't guarantee that it will be executed after exactly t seconds.

Another important question is what happens if we have time out of 0ms. Let's take an example

setTimeout(function(){
    console.log("world");
},0);
console.log("hello!");

Many people think that here we have a delay of 0ms so "world" will be printed first and then it will execute console.log("hello!") but that's wrong when we encounter setTimeout() it's going to register function in Web Apis and timer will be set to 0ms but it's going to expire immediately and function will be moved to callback queue but now it has to wait in callback queue until call stack becomes empty when we complete execution of console.log("hello!") call stack will be empty and only after that function will be pushed in the call stack and will be executed. I hope you got an answer to this question.