1.防抖
概念:持续触发事件时,一定时间内未触发事件才会执行函数。
适合的应用场景:input输入
实现防抖函数:
function debounce(fn,delay) {
let timer = null
return function() {
if(timer){
clearTimeout(timer)
}
timer = setTimeout(fn,delay)
}
}
使用时:
document.getElementById('btn').onclick=debounce(function () {
console.log('点击了');
},1000)
2.节流
概念:固定时间间隔内触发多少次事件,都只执行一次
适应的场景:scroll resize
实现节流函数:
function throttle(fn,delay){
let valid = true
return function() {
if(!valid){
//休息时间
return false
}
// 工作时间,执行函数并且在间隔期内把状态位设为无效
valid = false
setTimeout(() => {
fn()
valid = true;
}, delay)
}
}
使用时
document.getElementById('btn').onclick=throttle(function () {
console.log('点击了');
},1000)