UNPKG

debounce-microtasks

Version:

Debounce a function using microtasks instead of timers.

56 lines (55 loc) 1.59 kB
"use strict"; /** * @module * * A simple utility to debounce a function to the next microtask. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.debounceMicrotask = void 0; const enqueue = typeof queueMicrotask === "function" ? queueMicrotask : (fn) => Promise.resolve().then(fn); /** * Execute the function in the next microtask, if the function is called again * later in the event loop, push back the execution one more microtask * in the future. */ const debounceMicrotask = (fn, options) => { let queued = false; let { debounceLimit = 1000 } = options ?? {}; let currentArgs; return (...args) => { if (options?.updateArguments) { currentArgs = args; } else { currentArgs ??= args; } if (queued) return; if (debounceLimit-- <= 0) { switch (options?.limitAction) { case "ignore": return; case "invoke": return fn(...currentArgs); case "throw": default: throw new Error(`Maximum debounce limit reached.`); } } queued = true; enqueue(dequeue); function dequeue() { if (queued) { queued = false; enqueue(dequeue); } else { debounceLimit = options?.debounceLimit ?? 1000; fn(...currentArgs); } } }; }; exports.debounceMicrotask = debounceMicrotask;