防抖和节流函数

115 阅读1分钟

防抖函数

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

节流函数

function throttle(func,wait){
    let timeout = null
    return function(){
        let context = this
        let args = arguments
        if(!timeout){
            timeout = setTimeout(()=>{
                timeout = null
                func.apply(context,args)
            },wait)
        }
    }
}