@alwatr/wait
@alwatr/wait
offers a collection of utility functions to handle asynchronous execution flow effectively. It allows you to pause your code until specific conditions are met or certain events occur. This functionality aids in managing complex asynchronous scenarios and crafting intricate flows with ease. The functions can be used independently or combined for robust control over asynchronous operations.
Installation
npm install @alwatr/wait
yarn add @alwatr/wait
Usage
Each function within @alwatr/wait
returns a Promise that resolves when the specified waiting condition is met. Here's a breakdown of the available functions:
-
waitForTimeout(duration: number): Promise
-
waitForAnimationFrame(): Promise
-
Pauses execution until the next animation frame is scheduled, resolving with the current timestamp.
-
Useful for synchronizing UI updates with browser rendering.
-
Example:
import { waitForAnimationFrame } from '@alwatr/wait';
await waitForAnimationFrame();
-
waitForIdle(timeout?: number): Promise
-
Waits for the next idle period (when the browser is not busy), resolving with an IdleDeadline
object.
-
Optionally accepts a timeout value (in milliseconds) for maximum waiting time.
-
Ideal for executing tasks that don't impact user experience.
-
Example:
import { waitForIdle } from '@alwatr/wait';
await waitForIdle();
-
waitForDomEvent(element: HTMLElement, eventName: T): Promise<HTMLElementEventMap[T]>
-
Pauses execution until a specific DOM event is triggered on a provided element, resolving with the event object.
-
Example:
import { waitForDomEvent } from '@alwatr/wait';
const button = document.getElementById('myButton');
await waitForDomEvent(button, 'click');
-
waitForEvent(target: HasAddEventListener, eventName: string): Promise
-
More generic version of waitForDomEvent
, allowing waiting for any event on any object with an addEventListener
method.
-
Example:
import { waitForEvent } from '@alwatr/wait';
const server = http.createServer();
await waitForEvent(server, 'request');
-
waitForImmediate(): Promise
-
waitForMicrotask(): Promise
-
Similar to waitForImmediate
, but waits specifically for the next microtask queue.
-
Example:
import { waitForMicrotask } from '@alwatr/wait';
await waitForMicrotask();
Contributing
We welcome contributions to improve this package! Feel free to open bug reports, suggest new features, or submit pull requests following our contribution guidelines.
License:
This package is distributed under the MIT License.