UNPKG

debounce-microtasks

Version:

Debounce a function using microtasks instead of timers.

65 lines (64 loc) 1.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.debounceMicrotask = void 0; const DebounceMicrotask_js_1 = require("./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. */ 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 = (0, DebounceMicrotask_js_1.debounceMicrotask)((...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; }; }; exports.debounceMicrotask = debounceMicrotask;