防抖
概念
n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时
使用场景
频繁输入事件
实现
function debounce(fn, delay = 100) {
let timer = null
return function() {
if(timer){
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null
},delay)
}
}
节流
概念
n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效
场景
滚动加载事件
实现
// 节流函数
function throttle(fn, delay = 100) {
let timer = null
return function () {
if(timer){
return
}
timer = setTimeout(() =>{
fn.apply(this, arguments);
timer = null
},delay)
}
}