UNPKG

nexbounce

Version:

A debouncer library based on microtasks.

18 lines (17 loc) 477 B
export class Debouncer { #taskWatcher; #callLatest; #cancelPrevious; enqueue(task) { if (this.#taskWatcher !== undefined) this.#cancelPrevious?.(); this.#taskWatcher = new Promise((resolve, reject) => { this.#callLatest = resolve; this.#cancelPrevious = reject; }); this.#taskWatcher .then(task) .catch(() => {}) .finally(() => (this.#taskWatcher = undefined)); queueMicrotask(this.#callLatest); } }