Function scheduleIdleCallback

  • Queues a function to be called during a browser's idle periods. This enables developers to perform background and low priority work on the main event loop, without impacting latency-critical events such as animation and input response. Functions are generally called in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses.

    You can call scheduledleCallback() within an idle callback function to schedule another callback to take place no sooner than the next pass through the event loop.

    If the runtime does not support the requestIdleCallback it will fallback to use setTimeout with either the provided timeout or the current default idle timeout, which can be set via setDefaultIdleTimeout. It will always supply a deadline which indicates that the request timed out.

    Parameters

    • callback: IdleRequestCallback

      A reference to a function that should be called in the near future, when the event loop is idle. The callback function is passed an IdleDeadline object describing the amount of time available and whether or not the callback has been run because the timeout period expired.

    • Optional options: IdleRequestOptions

      Contains optional configuration parameters. Currently only one property is defined: timeout If the number of milliseconds represented by this parameter has elapsed and the callback has not already been called, then a task to execute the callback is queued in the event loop (even if doing so risks causing a negative performance impact). timeout must be a positive value or it is ignored.

    Returns ITimerHandler

    A handle which can be used to cancel the callback by passing it into the cancelIdleCallback() method.

    Since

    0.4.4

    Example

    let idleCalled = false;
    let idleTimedOut = false;
    let theIdleTimer = scheduleIdleCallback((idleDeadline: IdleDeadline) => {
    // This callback will be called when the system is idle (via requestIdleCallback) or after the provided timeout 100ms
    idleCalled = true;
    idleTimedOut = idleDeadline?.didTimeout;
    while ((idleDeadline.timeRemaining() > 0 || deadline.didTimeout)) {
    // Do some background operations while there is time remaining or we timed out
    // Unlike interval timers this callback will NOT be called again unless you call "refresh"
    // to restart it or create a new idle timer
    }
    }, 100);

    // Instead of calling cancelIdleCallback() with the returned value from requestIdleCallback() the returned
    // handler instance can be used instead to cancel the idle timer
    theIdleTimer.cancel();
    theIdleTimer.enabled; // false

    // You can start the timer via enabled
    theIdleTimer.enabled = true;

    // You can also "restart" the timer, whether it has previously triggered not not via the `refresh()`
    theIdleTimer.refresh();