/** * Throttle the given function to run at most every `period` milliseconds. */ export function throttle void>(fn: T, time: number): (...args: Parameters) => ReturnType { let pending = false; let timerId: ReturnType = null; let lastCallContext = null; let lastCallArgs: Parameters; const later = () => { timerId = null; if (pending) { fn.apply(lastCallContext, lastCallArgs); timerId = setTimeout(later, time); pending = false; } }; return (...args: Parameters) => { pending = true; lastCallContext = this; lastCallArgs = args; if (!timerId) { later(); } return timerId; }; }