UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

42 lines (38 loc) 959 B
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * 节流 * * 连续触发事件但是在 n 秒中只执行一次函数 * @param {Function} fn 主函数 * @param {number} time 间隔时间,单位 `ms` * @returns 闭包函数 * * @example * * ```ts * function count() { * console.log('xxxxx') * } * window.onscroll = throttle(count, 500) * ``` */ function throttle(fn, time) { var timer; return function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-this-alias var that = this; // const args = [...arguments]; if (!timer) { timer = setTimeout(function () { timer = null; // 注意,一定要先置为null,再执行fn fn.apply(that, args); }, time); } }; } exports.throttle = throttle;