防抖

2021-10-28  本文已影响0人  tenro

非立即执行

function debounce(fn, wait){
    let timeout;
    return function(){
        let context = this;
        let args = arguments;
          
        if(timeout) clearTimeout(timeout)
        
        timeout = setTimeout(() => {
            fn.apply(context, args)
        })
}

立即执行

function debounce(fn, wait){
    let timeout;
    return function(){
        let context = this;
        let args = arguments;
          
        if(timeout) clearTimeout(timeout)
        let callNow = !timeout

        timeout = setTimeout(() => {
            timeout = null
        })
        
        if (callNow) fn.apply(context, args)
}
上一篇 下一篇

猜你喜欢

热点阅读