UNPKG

es-toolkit

Version:

A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.

32 lines (27 loc) 931 B
'use strict'; Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); const debounce = require('./debounce.js'); function throttle(func, throttleMs, { signal, edges = ['leading', 'trailing'] } = {}) { let pendingAt = null; const debounced = debounce.debounce(function (...args) { pendingAt = Date.now(); func.apply(this, args); }, throttleMs, { signal, edges }); const throttled = function (...args) { if (pendingAt == null) { pendingAt = Date.now(); } if (Date.now() - pendingAt >= throttleMs) { pendingAt = Date.now(); func.apply(this, args); debounced.cancel(); debounced.schedule(); return; } debounced.apply(this, args); }; throttled.cancel = debounced.cancel; throttled.flush = debounced.flush; return throttled; } exports.throttle = throttle;