Home >Web Front-end >JS Tutorial >setTimeout() takes more time than given time in param

setTimeout() takes more time than given time in param

Barbara Streisand
Barbara StreisandOriginal
2025-01-04 21:48:401013browse

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)

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.

The above is the detailed content of setTimeout() takes more time than given time in param. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn