防抖
- 函数被触发后等待一段时间才执行
- 如果这段等待的时间内函数再被触发,重新计时
直接上代码:
const debounce = (func, wait = 350) => {
let timer = 0;
return (...args) => {
// 如果这段等待的时间内函数再被触发,重新计时
if(timer){
clearTimeout(timer);
}
// 函数被触发后等待一段时间才执行
timer = setTimeout(()=>{
func.apply(this, args)
}, wait);
};
};
使用:
const fn = debounce(() => {...}, 500);
节流
-
函数触发后立即执行一次
-
在设定的时间内无论函数触发多少次都不会执行
-
过了设定的时间,再次触发函数才会执行一次
const throttle = (func, wait = 350) => { let lastTime = 0; return (...args) => { const now = new Date().getTime(); if (now - lastTime > wait) { // 第一次执行时因为lastTime = 0,所以肯定为true,立即执行 // 之后因为lastTime = now,每次至少要间隔wait才能再次执行 func.apply(this, args); lastTime = now; } }; };
使用:
const fn = throttle(() => {...}, 500);