/** * 节流函数 * 实现原理: 利用时间戳和定时器 * 应用场景: 拖拽、缩放、动画等 * 实现方式: 通过闭包保存一个标记来判断是否需要执行函数 * * @example * const resizeFunc = throttle((e) => { * console.log('resize'); * }, 1000); * window.addEventListener('resize', resizeFunc); * */ /** * 节流函数 * @param func 要执行的函数 * @param wait 等待时间 * @param options 选项 * @param options.leading 是否立即执行 (true: leading模式,false: trailing模式) * @param options.trailing 是否在最后一次调用后执行一次 (true: trailing模式,false: 不执行) * @returns 节流函数 */ declare function throttle any>(func: T, wait: number, options?: { leading?: boolean; trailing?: boolean; }): T & { cancel: () => void; }; /** * 节流函数 * // 1.普通节流 function throttle(func, wait) { let timer = null; return (...args) => { if (timer) return; timer = setTimeout(() => { func.apply(this, args); timer = null; }, wait); } } // 2.立即执行一次 function throttle(func, wait) { let timer = null; let last = 0; // 上一次执行的时间 return (...args) => { clearTimeout(timer); let now = Date.now(); // 当前时间 // 距离上次执行时间大于等于wait时,执行函数 if (now - last >= wait) { func.apply(this, args); last = now; // 更新上一次执行时间 } else { timer = setTimeout(() => { func.apply(this, args); last = Date.now(); }, wait); } } } */ export { throttle as default };