UNPKG

debounce-microtasks

Version:

Debounce a function using microtasks instead of timers.

52 lines (51 loc) 1.44 kB
/** * @module * * A simple utility to debounce a function to the next microtask. */ 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. */ export 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); } } }; };