DEV Community

Trishank Sharma
Trishank Sharma

Posted on

setTimeout() takes more time than given time in param

setTimeout is not part of core JavaScript. Yes, you heard right. It is part of the web APIs provided by the browser (in a web environment) or the Node.js APIs in a server-side environment.
As we all know, the setTimeout method takes the CB function as a parameter. The other parameter is the time in ms after which the CB must be executed.
But wait, It is not necessary that setTimeout execute always at given time params. If our call stack or say main thread is blocked by any piece of code then setTimeout is immediately executed in the call stack after the blocking code is complete. Until then, it remains stored in the Browser Callback queue or Task Queue.

console.log("HELLO");
setTimeout(() => console.log("Timeout executed"), 5000); //should be execute after 5sec
let start = new Date().getTime();
let end= start;
while (end < start + 10000){
  end= new Date.getTime();
} //This loop will block the main thread for 10sec
 console.log("Time Expire");

//output---
//HELLO
//Time Expire
//Timeout executed  (Immediately just after Time expire)
Enter fullscreen mode Exit fullscreen mode

There is one case also, what if we provide 0ms time in setTimeout. Is it execute in sequence manner like normal code execution.
The answer is no because setTimeout is first go the CB queue unlike other function which execute immediately first in call stack.

Top comments (0)