UNPKG

@shopify/cli-kit

Version:

A set of utilities, interfaces, and models that are common across all the platform features

48 lines 1.65 kB
export function throttle(func, wait, { leading = true, trailing = true } = {}) { let lastArgs; let result; let context; let timeout = null; let previous = 0; function later() { previous = leading === false ? 0 : Date.now(); timeout = null; if (lastArgs) { result = func.apply(context, lastArgs); // If the throttled function returns a promise, swallow rejections to // prevent unhandled promise rejections (the caller already .catch()'d // the leading-edge invocation and has no reference to trailing calls). if (result && typeof result.catch === 'function') { result.catch(() => { }); } } context = null; lastArgs = null; } return function (...args) { const now = Date.now(); if (!previous && leading === false) previous = now; const remaining = wait - (now - previous); // eslint-disable-next-line @typescript-eslint/no-this-alias, consistent-this context = this; lastArgs = args; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; if (lastArgs) { result = func.apply(context, lastArgs); } context = null; lastArgs = null; } else if (!timeout && trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; } //# sourceMappingURL=throttle.js.map