Gustavo Máximo
Gustavo Máximo

Reputation: 6140

Is there a better alternative to setTimeOut(fn, 0)?

Is there another way of achieving the same behavior of scheduling a callback function on the JavaScript's message queue to be run after the current stack is empty?

In other words, is there a way, be it with Promises or third-party packages to push a callback to the task queue so that it runs after the current stack is empty?

In other words, what are some equivalents/alternatives to passing 0 to setTimeout to take advantage of the asynchronous callback?

Answers for all environments and all ECMAScript versions are welcome.

Upvotes: 12

Views: 18238

Answers (2)

Steve
Steve

Reputation: 8809

Use queueMicrotask. It runs before control is returned to the event loop, so it will be scheduled to execute before setTimeout(fn, 0).

Example:

setTimeout(() => console.log('setTimeout'), 0)
queueMicrotask(() => console.log('queueMicrotask'))

Output:

queueMicrotask
setTimeout

In terms of timing, queueMicrotask(fn) is equivalent to Promise.resolve().then(fn), suggesting that Promises are scheduled using queueMicrotask.

Upvotes: 2

ikhvjs
ikhvjs

Reputation: 5947

In nodejs environment, you can do the async tasks in the following way.

Ref. https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

setImmediate(() => console.log("setImmediate"));
setTimeout(() => console.log("setTimeout"));
Promise.resolve().then(() => console.log("Promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");

Output:

sync
nextTick
Promise
setTimeout
setImmediate

In modern browswer, you can do the async tasks in the following way.

setTimeout(() => console.log("setTimeout"));
Promise.resolve().then(() => console.log("Promise"));
console.log("sync");

Upvotes: 5

Related Questions