Skip to main content

defer()

defer<Args>(func, ...args): Timeout

Defers invoking the function until the current call stack has cleared.

DEPRECATED

Use setTimeout(fn, 0) directly instead.


Type Parameters​

Args: Args extends unknown[]​


Parameters​

func: (...args) => void​

The function to defer.

args: ...Args​

The arguments to invoke the function with.


Returns: Timeout​

The timer id.


See Also​

setTimeout() - MDN


Since​

2.0.0


Also known as​

defer (Lodash, es-toolkit) · ❌ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Example​

// ❌ Deprecated approach
defer(console.log, 'deferred');

// βœ… Recommended approach
setTimeout(() => console.log('deferred'), 0);

How it works?​

Defers invoking func until the current call stack clears. Deprecated: Use setTimeout(fn, 0) or queueMicrotask() directly.

Native Equivalent​

// ❌ defer(fn)
// βœ… setTimeout(fn, 0)
// βœ… queueMicrotask(fn)

Use Cases​

Defer execution πŸ“Œβ€‹

Execute function after current call stack.

queueMicrotask(() => {
console.log("Deferred");
});

Defer to next tick​

Schedule for next event loop iteration.

setTimeout(() => {
updateUI();
}, 0);

Non-blocking operation​

Allow current execution to complete first.

Promise.resolve().then(() => {
heavyComputation();
});