UNPKG

es-next-tools

Version:

A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.

21 lines (20 loc) 701 B
/** * Creates a throttled function that only invokes the original function at most once per every `wait` milliseconds. * @param {T} fn - The function to throttle. * @param {number} wait - The number of milliseconds to throttle invocations to. * @returns {Function} A new, throttled function. * @template T * @example * const throttledFn = throttle(() => console.log('Throttled'), 1000); * // Calling throttledFn multiple times within 1 second will only log once */ export function throttle(fn, wait) { let lastCall = 0; return (...args) => { const now = Date.now(); if (now - lastCall >= wait) { lastCall = now; fn(...args); } }; }