// 防抖函數(shù),頻繁操作,只執(zhí)行最后一次操作
function xx(fun,t){
let timer
return function(){
if(timer){
clearTimeout(timer)
}
timer=setTimeout(function(){fun()},t)
}
}
// 節(jié)流函數(shù),頻繁操作,只執(zhí)行一次操作
function xx2(fun,t){
let timer = null
return function(){
if(!timer){
timer=setTimeout(function(){
fun()
timer = null // 在setTimeout中,執(zhí)行clearTimeout不起作用,所以需要將timer置為null
},t)
}
}
}
function log(){
console.log('log')
}
document.querySelector('.btn1').addEventListener('click',xx(log,500))
document.querySelector('.btn2').addEventListener('click',xx2(log,500))