UNPKG

@n1ru4l/in-memory-live-query-store

Version:

[![npm version](https://img.shields.io/npm/v/@n1ru4l/in-memory-live-query-store.svg)](https://www.npmjs.com/package/@n1ru4l/in-memory-live-query-store) [![npm downloads](https://img.shields.io/npm/dm/@n1ru4l/in-memory-live-query-store.svg)](https://www.np

41 lines (40 loc) 1.02 kB
/** * Creates a throttled function that only invokes func at most once per every wait milliseconds. */ export const throttle = (fn, wait) => { let timeout; let lastCalled = 0; let cancelled = false; const exec = (...args) => { if (!cancelled) { fn(...args); lastCalled = Date.now(); } }; const run = (...args) => { if (cancelled) { return; } const timeToNextTick = Math.max(0, wait - (Date.now() - lastCalled)); if (!timeToNextTick) { // first execution, or wait === 0 exec(...args); } else { clearTimeout(timeout); timeout = setTimeout(() => { if (Date.now() - lastCalled >= wait) { exec(...args); } }, timeToNextTick); } }; const cancel = () => { cancelled = true; clearTimeout(timeout); }; return { run, cancel, }; };