UNPKG

debounce-microtasks

Version:

Debounce a function using microtasks instead of timers.

61 lines (60 loc) 1.6 kB
import { debounceMicrotask as debounce, } from "./DebounceMicrotask.js"; /** * @module * * A simple utility to debounce a function to the next microtask, returning * promises that resolves with the next execution. */ /** * 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. * * The debounced function will return a promise that resolves with the return * value when the specified function is executed, while the non-promise version * has no way to capture the return values. */ export const debounceMicrotask = (fn, options) => { let resolve; let reject; let running = false; let settled = false; let promise = new Promise((res, rej) => { resolve = res; reject = rej; }); const debounceFn = debounce((...args) => { if (running) return; running = true; try { resolve(fn(...args)); } catch (e) { reject(e); } finally { running = false; settled = true; } }, options); return (...args) => { if (settled) { promise = new Promise((res, rej) => { resolve = res; reject = rej; }); settled = false; } else { try { debounceFn(...args); } catch (e) { reject(e); settled = true; } } return promise; }; };