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