防抖和节流

56 阅读1分钟

实现防抖和节流

防抖节流能有效的提高性能

function debounce(fn,wait = 500){
    let timer = null
    return function (){
        if (timer){
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            fn.apply(this,arguments)
        },wait)
    }
}
document.getElementById('_input').addEventListener('keyup',debounce(function (){
    console.log(this.value)
}))
//节流---一段时间执行一次
function throttle(fn,wait=100){
    let timer = null
    return function (){
        if (timer) return
        timer = setTimeout(()=>{
            fn.apply(this,arguments)
            timer = null
        },wait)
    }
}