Navigation

Deferral utilities

inTimeout#

inTimeout(ms) returns a lazy promise that fires with a value of type void in a setTimeout callback. If unsubscribed before it fires, calls clearTimeout.

To sleep for 1 second in the middle of a generator function, you would

yield* inTimeout(1000);

With native promises, you could do the following:

try {
  return await promise;
} finally {
  // Wait for `anotherPromise`, then pass on result of `promise`.
  await anotherPromise;
}

You can use the same pattern to delay a lazy promise:

try {
  return yield* lazyPromise;
} finally {
  // Wait for a second, then pass on the result of `lazyPromise`.
  yield* inTimeout(1000);
}

or equivalently,

lazyPromise.finally(() => inTimeout(1000));

inMicrotask#

inMicrotask() returns a lazy promise that fires with a value of type void in a queueMicrotask callback. If the lazy promise is unsubscribed before firing, the callback cannot be un-scheduled, but becomes a no-op.

If you want a LazyPromise to fire in a microtask like a native promise, add .finally(inMicrotask), similarly to what we did above with inTimeout.

inAnimationFrame#

inAnimationFrame() returns a lazy promise that fires with a value of type DOMHighResTimeStamp in a requestAnimationFrame callback. If unsubscribed before it fires, calls cancelAnimationFrame.

Not available in Node.

inIdleCallback#

inIdleCallback({ timeout }) returns a lazy promise that fires with a value of type IdleDeadline in a requestIdleCallback callback, passing on the options object. If unsubscribed before it fires, calls cancelIdleCallback.

Not available in Node, limited availability in browsers.

inImmediate#

inImmediate() returns a lazy promise that fires with a value of type void in a setImmediate callback. If unsubscribed before it fires, calls clearImmediate.

Not available in modern browsers.

inNextTick#

inNextTick() returns a lazy promise that fires with a value of type void in a process.nextTick callback. If the lazy promise is unsubscribed before firing, the callback cannot be un-scheduled, but becomes a no-op.

Not available in browsers.

inMessageChannel#

inMessageChannel() posts a message in MessageChannel and resolves with a value of type void when it receives the message back, unless by then it has been unsubscribed. In Node, it keeps the process alive while messages are pending and unrefs the port once the queue is empty.

inScheduled#

inScheduled({ priority }) returns a lazy promise that fires with a value of type void in a scheduler.postTask callback. If unsubscribed before it fires, cancels the task using an AbortSignal. Takes an options object with task priority (“user-visible” by default).

Limited availability in browsers.