1.防抖
触发事件后在n秒内函数只执行一次,如果在n秒内又触发了事件,则会重新计算时间
<button id="btn">点击</button>
<script>
function fun (fn,awaits){
var times = null
return function(){
let This = this
if(times) {
clearTimeout(times)
}
times = setTimeout(function(){
fn.apply(This,arguments)
times = null
},awaits)
}
}
let btn = document.getElementById('btn')
function a (){
console.log('123')
}
btn.onclick = fun(a,1000)
</script>
节流
触发事件,但是在n秒内只执行一次
<button id="btn">点击</button>
<script>
function fun (fn,awaits){
var times = null
return function(){
let This = this
if(times) return
times = setTimeout(function(){
fn.apply(This,arguments)
// console.log(times)
times = null
},awaits)
}
}
let btn = document.getElementById('btn')
function a (){
console.log('123')
}
btn.onclick = fun(a,3000)
</script>