节流(一段时间执行一次之后,就不执行第二次)
function throttle(fn,delay){
let canUse=true
return function(){
if(canUse){
fn.apply(this,arguments)
canUse=false
setTimeout(()=>canUse=true,delay)
}
}
}
const throttled=throttle(()=>console.log('hi'))
throttled()
throttled()
防抖(一段时间会等,然后带着一起做)
function debounce(fn,delay){
let timeId=null
return function(){
const content=this
if(timeId){window.clearTimeout(timeId)}
timrId=setTimeout(()=>{
fn.apply(content,arguments)
timeId=null
},delay)
}
}
const debounced=debounce(()=>console.log('hi'))
debounced()
debounced()