Skip to content

How to execute setTimeout function immediately after the delay?

I want to execute setTimeout after the delay and not wait for it to be called from the message queue after all the other functions have executed. Please refer the code below:

let test = function(){ console.log('test') }
setTimeout(() => console.log('hi'), 2000)
this code takes more than 2 seconds to execute;

How to get setTimeout after 2 seconds instead of at the end ?


I thought I would mention that if those test() calls do not perform DOM operations you could possibly move them to a worker.

Web Workers allow running code on a background thread that doesn’t block your main UI thread. I’ve created a quick example that runs a synchronous task of arbitrary duration on a worker thread. On the main thread setInterval and setTimeout calls are running uninterrupted.

See it in action.


let interval = setInterval(() => console.log("Not blocked"), 500);
console.log("Scheduling to run in 2 seconds");
setTimeout(() => {
  console.log("2 seconds passed. Running scheduled task! ");
}, 2000);
let longTaskRunner = new Worker("./src/worker.js");
let taskDuration = 3;
  `Starting synchronous task that takes more than ${taskDuration} seconds`
longTaskRunner.onmessage = function(e) {
  console.log(`Long task completed in ${} seconds`);
longTaskRunner.onerror = function(e) {


self.onmessage = function(e) {
  const runFor = * 1000;
  let startedAt =;
  let timeElapsed = 0;
  while (timeElapsed < runFor) {
    timeElapsed = - startedAt;
  self.postMessage(timeElapsed / 1000);