UNPKG

hd-utils

Version:

A handy utils for modern JS developers

31 lines (30 loc) 973 B
/** * * @description it will throttlePromise the call of the function param to wait for n seconds. * @example const func = (hello: string) => { console.log(new Date().getTime(), '>>>', hello) } * const thrFunc = throttlePromise(func, 1000) * thrFunc('hello 1') */ const throttlePromise = (func, waitFor = 200) => { const now = () => new Date().getTime(); let startTime = now() - waitFor; let timeout; const resetStartTime = () => (startTime = now()); return (...args) => new Promise(resolve => { const timeLeft = startTime + waitFor - now(); if (timeout) { clearTimeout(timeout); } if (startTime + waitFor <= now()) { resetStartTime(); resolve(func(...args)); } else { timeout = setTimeout(() => { resetStartTime(); resolve(func(...args)); }, timeLeft); } }); }; export default throttlePromise;