函数防抖
定义:触发函数调用后,原本为n秒后就执行回调函数,如果在等待的n秒内函数再次被触发,则计时器重新计时
代码实现
function antiShake(fn,time){
let id = null
return function(){
if(id){
window.clearTimeout(id)
console.log('你被清掉准备重新计时了')
}
id = setTimeout(()=>{
fn.apply(this,arguments)
id = null
},time)
}
}
let ations = antiShake(()=>{console.log('test')},3000)
ations()
ations()
函数节流
定义:触发函数调用后,n秒内不可再触发该函数
代码实现
function throttle (fn, time) {
let canUse = true
return function () {
if (canUse) {
fn.apply(this, arguments)
canUse = false
setTimeout(() => {
canUse = true
}, time)
} else {
console.log('技能CD中,稍后再试')
}
}
}
let ations = throttle(() => {
console.log('test')
}, 4000)
ations()
ations()