什么是函数节流
打个很形象的比喻来说,函数节流就相当于技能CD,没CD完技能怎么也放不出,CD完之后你随时可以放。
函数节流:
var cd = ture
button.onclick = ()=> {
if(cd){
fn()
cd = false
setTimeout(()=> {
cd = ture
},1000)
}
}
然后把它封装成函数
function throttle(fn, delay){
let cd= true
return function(){
if(cd){
fn.apply(this, arguments)
cd= false
setTimeout(()=>cd= true, delay)
}
}
}
什么是函数防抖
函数防抖,就相当于给中了debuff,在中一次就重新刷新debuff持续时间,只有持续时间内没有再吃debuff才能消失。
函数防抖:
var debuff = null
button.onclick = ()=> {
if(debuff){
window.clearTimeout(debuff)
}
debuff = setTimeout(()=> {
fn()
debuff = null
},10000)
}
同样把它封装成函数
function debounce(fn, delay){
let debuff = null
return function(){
if(debuff ){
window.clearTimeout(debuff )
}
debuff = setTimeout(()=>{
fn.apply(this, arguments)
debuff = null
},delay)
}
}
网友评论