Skip to content

whenIdle

Runs callback when the browser is idle, with requestIdleCallback, for work that can wait (prefetching, analytics, warming a cache).

Where requestIdleCallback does not exist (Safari, Node.js), it falls back to setTimeout, so the callback still runs, after the current task.

Available since v3.1.5

import { whenIdle } from '@helpers4/browser';
// or, from the all-in-one package (same code, one install):
import { whenIdle } from 'helpers4/browser';
whenIdle(callback: function, options: WhenIdleOptions): function
ParameterTypeDescription
callbackfunctionThe work to run
optionsWhenIdleOptionsTimeout and cancellation — see WhenIdleOptions

function — A function that cancels the callback if it has not run yet

Runs when the browser is idle, or after the timeout at the latest.

whenIdle(() => preloadImages(nextScreens), { timeout: 2000 });

The returned function cancels the callback if it has not run yet.

const cancel = whenIdle(warmCache);
cancel();

Options for whenIdle.

interface WhenIdleOptions {
  signal?: AbortSignalLike;
  timeout?: number;
}

View source on GitHub