写在前面:
兄弟们,我手里有个长期项目,考虑接私活的可以看看我GitHub!
https://github.com/ccy-233/coder2retire
Lodash 是一个一致性、[模块化]、高性能的 JavaScript 实用工具库。
$ npm i -g npm$ npm i --save lodash
在这个示例中,我们希望用户在[输入框]中停止输入 500 毫秒后才执行搜索操作,避免频繁请求.
在这个示例中,我们希望当用户滚动页面时,每隔 1 秒才记录一次滚动事件,避免频繁触发回调函数。
Scroll down to see the effect
解释:
throttledScroll
函数会在 1 秒内最多触发一次,避免滚动时回调函数被频繁调用。leading
和 trailing
选项假设我们希望在用户第一次触发事件时立即执行函数,并在停止触发 1 秒后再次执行。
// 防抖函数export function debounce(fn: Function, delay: number) { let timer: ReturnType | null = null; return function (this: any, ...args: any[]) { // 清除上一个定时器 if (timer) { clearTimeout(timer); } // 设置新的定时器 timer = setTimeout(() => { fn.apply(this, args); // 使用apply确保this和参数正确传递 }, delay); };} // 节流函数export function throttle(fn: Function, delay: number) { let lastTime = 0; return function (this: any, ...args: any[]) { const now = Date.now(); // 如果距离上次执行时间已超过指定时间间隔,则执行函数 if (now - lastTime >= delay) { lastTime = now; // 更新上次执行时间 fn.apply(this, args); } };}
方式一:
滚动内容
滚动内容
debounce
):手抖了。。。多点了好几次,一定时间内只执行一次。(年纪大了手抖)
throttle
):好比点了两次下拉刷新列表页面,他不会马上直接执行两次,是在你定义的一定时间间隔前提前,先执行第一次在执行第二次