Skip to content
Advertisement

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)

test();
test();
test();
.
.
.
.
this code takes more than 2 seconds to execute;

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

Advertisement

Answer

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.

index.js

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;
console.log(
  `Starting synchronous task that takes more than ${taskDuration} seconds`
);

longTaskRunner.postMessage(taskDuration);
longTaskRunner.onmessage = function(e) {
  console.log(`Long task completed in ${e.data} seconds`);
  clearInterval(interval);
};
longTaskRunner.onerror = function(e) {
  console.log(e.message);
};

worker.js

self.onmessage = function(e) {
  const runFor = e.data * 1000;
  let startedAt = Date.now();
  let timeElapsed = 0;

  while (timeElapsed < runFor) {
    timeElapsed = Date.now() - startedAt;
  }

  self.postMessage(timeElapsed / 1000);
};
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement