UNPKG

@uwdata/mosaic-core

Version:

Scalable and extensible linked data views.

51 lines 1.5 kB
const NIL = {}; /** * Throttle invocations of a callback function. The callback must return * a Promise. Upon repeated invocation, the callback will not be invoked * until a prior Promise resolves. If multiple invocations occurs while * waiting, only the most recent invocation will be pending. * @param callback The callback function. * @param debounce Flag indicating if invocations * should also be debounced within the current animation frame. * @returns A new function that throttles access to the callback. */ export function throttle(callback, debounce = false) { let curr; let next; let pending = NIL; function invoke(event) { curr = callback(event) ?.catch(() => { }) .finally(() => { if (next) { const { event: value } = next; next = null; invoke(value); } else { curr = null; } }) || null; } function enqueue(event) { next = { event }; } function process(event) { if (curr) enqueue(event); else invoke(event); } function delay(event) { if (pending !== event) { requestAnimationFrame(() => { const e = pending; pending = NIL; process(e); }); } pending = event; } return debounce ? delay : process; } //# sourceMappingURL=throttle.js.map