Options
All
  • Public
  • Public/Protected
  • All
Menu

Module "delayedCallbacks"

module

Contains adapter functions that allows you to switch into another context when you subscribe the returned PromiseLikes. For example, in async functions, if you want to execute part of your logic inside an animation frame, you may now use a simple loop inside the asynchronous function.

import { ICancellationToken, requestAnimationFrameAsync } from "tasklike-promise-library";

async function playAnimation(cancellationToken?: ICancellationToken): Promise<void> {
    cancellationToken && cancellationToken.throwIfCancellationRequested();
    let prevTime = performance.now();
    let currentWidth = 0;
    const panel = document.querySelector("div.panel");
    while (!cancellationToken || !cancellationToken.isCancellationRequested) {
        const animationFrame = await requestAnimationFrameAsync(cancellationToken);
        // From now on, we are inside RAF callback.
        // `animationFrame` contains the information passed from RAF callback,
        // basically, the start time of the animation frame.
        // Make some animation here.
        const frameDuration = animationFrame.time - prevTime;
        // Let the width of .panel increase by 10 pixel/sec.
        currentWidth += frameDuration * 10 * frameDuration / 1000;
        panel.styles.with = Math.round(currentWidth) + "px";
        prevTime = animationFrame.time;
        // End of RAF callback.
        // (More precisely, the callback stop at the next `await requestAnimationFrameAsync` expression.)
        // The next `await requestAnimationFrameAsync` expression will let us enter another RAF callback.
        // To exit the current RAF callback and enter another arbitrary asynchronous callback in the same async function,
        // Use `yielded()` or `delay(0)` from `"common"` module.
    }
}

Index

Functions

requestAnimationFrameAsync

requestIdleCallbackAsync

setTimeoutAsync

  • Gets a PromiseLike that resolves inside window.setTimeout callback.

    remarks

    Compared with {@link delay}, this function is more low-level and you should prefer to use {@link delay} when possible.

    Parameters

    • milliseconds: number

      the delay in milliseconds before the PromiseLike resolves.

    • Optional cancellationToken: ICancellationToken

      a token used to cancel the timeout with window.clearTimeout.

    Returns IConfigurablePromiseLike<number>

    a PromiseLike that resolves inside window.setTimeout callback. Resolved value is the timeout ID returned from window.setTimeout.

Generated using TypeDoc