UNPKG

ts-prime

Version:

A utility library for JavaScript and Typescript.

45 lines (44 loc) 1.32 kB
/** * The Debounce technique allow us to “group” multiple sequential calls in a single one. * @description * You can find great article that explains how throttle works [here](https://css-tricks.com/debouncing-throttling-explained-examples/) * @param func - Any provided function * @param debounceTimeMs - duration in milliseconds * @signature * P.throttle(func, throttleTimeMs) * @example * // Execute log * P.throttle(console.log, 1000) * @category Function */ import { purry } from "./purry"; export function throttle() { return purry(__throttle, arguments); } function __throttle(func, throttleTimeMs) { // tslint:disable: no-let var lastExec = null; var result = null; return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (result == null) { lastExec = Date.now(); result = { r: func.apply(void 0, args), }; return result.r; } var diff = Date.now() - lastExec; if (diff >= throttleTimeMs) { lastExec = Date.now(); result = { r: func.apply(void 0, args), }; return result.r; } return result.r; }; }