防抖和节流的实现。

防抖

function Throttle(fun, t) {
    
    
    let timeout; //setTimeout的标记,最后清除
    return function () {
    
    
        if (!timeout) {
    
    
            timeout = setTimeout(() => {
    
    
                timeout = null
            }, t)
            fun()//执行函数
        }
    }
}
//<button id="element">节流</button>
document.getElementById('element').onclick = Throttle(() => {
    
    
    console.log(1)
}, 2000)

节流

function Shake(fun,t) {
    
    
        let timeout
        return function () {
    
    
            if(!timeout){
    
    
                timeout = setTimeout(()=>{
    
    
                    timeout=null
                },t)
                fun(arguments)
            }else{
    
    
                clearTimeout(timeout)
                timeout = setTimeout(()=>{
    
    
                    timeout=null
            },t)
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46672781/article/details/127759119