Skip to content

defer()

Eugene Lazutkin edited this page Feb 25, 2026 · 7 revisions

Description

The defer function is a utility that allows you to execute a given function after the current call stack has cleared. This is particularly useful for deferring execution until the browser is idle or for scheduling a function to run at a later time without blocking the main thread.

Key features

  • Idle Scheduling: Utilizes requestIdleCallback if available, falling back to setTimeout or setImmediate to ensure compatibility across environments.
  • Non-blocking: Ensures that the function execution does not interfere with the main thread, allowing for smoother user experiences.

Technical specifications

defer is available as a named and default export.

defer(fn);

defer(fn)

  • Parameters:
    • fn: The function to be executed after the current call stack. It will be called with no arguments and its return value will be ignored.
  • Return Value: Returns undefined as the function is executed asynchronously.

scheduleDefer(fn)

A promise-based version of defer. Schedules a function to be called at the next available time and returns a promise.

  • Parameters:
    • fn: The function to schedule. If null or undefined, the promise resolves with an empty array ([]).
  • Return Value: Returns a Promise that resolves with the return value of fn(), or rejects if fn() throws.

Usage instructions

To use the defer function, import it into your project and pass the function you want to defer:

import defer, {scheduleDefer} from 'time-queues/defer.js';

const log = () => console.log('Function executed!');

defer(log); // Will execute log after the current call stack is cleared

// Promise-based version
const result = await scheduleDefer(() => 'done');
console.log(result); // 'done'

Troubleshooting

  • Function Not Executing: Ensure that the function passed to defer is defined and can be executed without errors.
  • Compatibility Issues: If requestIdleCallback is not supported, ensure that the fallback methods are functioning as expected.

See Also

  • sleep() - Promise-based delay
  • IdleQueue - Browser idle queue (uses defer internally)

Clone this wiki locally