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 ?

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);
};

Scheduling: setTimeout and setInterval, We may decide to execute a function not right now, but at a certain time later. setTimeout allows us to run a function once after the interval of time. let delay = 5000 ; let timerId = setTimeout ( function request ( ) { send� Zero delay scheduling with setTimeout(func, 0) (the same as setTimeout(func)) is used to schedule the call “as soon as possible, but after the current script is complete”. The browser limits the minimal delay for five or more nested call of setTimeout or for setInterval (after 5th call) to 4ms.

You may not need setTimeout. Instead return a promise from test function and do rest of the things inside then which will only work once test is resolved

let test = function() {
  return new Promise(function(resolve, reject) {
    console.log('test');
    resolve('test executed')
  })
}


test().then(function(data) {
  console.log(data)
});

JavaScript setTimeout() Function Examples, To demonstrate the concept, the following demo displays a popup, two The makeTalk function is then executed by setTimeout with a delay of one second: re-run the Pen using the button in the bottom right of the embed.)� The setTimeout() and setInterval() are two methods you can use to schedule tasks in JavaScript. This tutorial will show you how to do it. It will introduce you both methods. It will show you how…

If the chain of tests is consuming more than 2000ms of CPU time synchronously ("blocking"), I don't think it's possible like that - the best you could do is check in test (or in a function wrapped around it) whether the time difference between the start (where your setTimeout is currently) and the current time is more than 2 seconds - if so, execute the function. For example:

console.log('start');
let hasRun = false;
const fnToRunLater = () => console.log('hi');
const startTime = Date.now();
function test() {
  const now = Date.now();
  if (!hasRun && now - startTime > 2000) {
    fnToRunLater();
    hasRun = true;
  }
  for (let i = 0; i < 2e8; i++) {
    // some expensive operations
  }
}
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
if (!hasRun) {
  fnToRunLater();
}
console.log('done');

(warning: below snippet containing the code above will block your browser for a bit, depending on your hardware)

// look at the timing in your browser console, not the snippet console

console.log('start');
let hasRun = false;
const fnToRunLater = () => console.log('hi');
const startTime = Date.now();
function test() {
  const now = Date.now();
  if (!hasRun && now - startTime > 2000) {
    fnToRunLater();
    hasRun = true;
  }
  for (let i = 0; i < 2e8; i++) {
    // some expensive operations
  }
}
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
test();
if (!hasRun) {
  fnToRunLater();
}
console.log('done');

Cooperative asynchronous JavaScript: Timeouts and intervals , The callbacks you pass to these functions cannot run until the stack on If you execute code like setTimeout(fn, 0) but then immediately after run Recursive setTimeout() guarantees the same delay between the executions. In this video, learn how to use timing functions in Node.js. The timing functions setTimeout, clearTimeout, setInterval, and clearInterval are popular browser features but are also available in Node.js. Also, learn how to create a delay using the setTimeout function.

JavaScript Timer Functions, Executing Code After a Delay. The setTimeout() function is used to execute a function or specified piece of code just once after a certain period of time. Its basic� This will execute the function once immediately and then the setInterval() function can be set with the required callback. A new function is created which encloses the invoking of the function first and then calls the setInterval() function next. This will help to simulate the setInterval() function without a delay for the first time. Example:

JavaScript setTimeout, cb is a callback function to be executed after the timer expires. delay is the time in milliseconds that the timer should wait before executing the callback function. If� The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. Tip: 1000 ms = 1 second. Tip: The function is only executed once. If you need to repeat execution, use the setInterval() method. Tip: Use the clearTimeout() method to prevent the function from running.

The delay on setTimeout() and setInterval() is just a suggestion, The setTimeout() and setInterval() methods allow you to run a function after a certain number of milliseconds (repeatedly, in the case of� If you execute code like setTimeout(fn, 0) but then immediately after run a loop that counts from 1 to 10 billion, your callback will be executed after a few seconds. In the following example, the browser will wait two seconds before executing the anonymous function, then will display the alert message ( see it running live , and see the source

Comments
  • Even other non-event based execution also doesn't guarantee that the code will for sure be executed at some exact time. However to get close to a 2 second delay, you can have a 1.5 seconds delay and then run a while loop which will block other execution, have a counter of what 2 seconds delay would be in milliseconds, check for the time in milliseconds and then run the code.
  • for that to happen, your code needs to be asynchronous so that they can add any other function in stack
  • If you are blocking thread, there is no way other code could run. You must have all of the subsequent code be non-blocking then.