定时器实现防抖节流

1.防抖
定义:在一段时间内只在最后一次触发方法
场景:点击按钮请求;搜索框输入查询,用户最后一次输入完,再发送请求

<body>
    <button>点击<button>
</body>
<script>

const btn = document.querySelector('button')
function getChange(value) {
    
    
    console.log('点击了',value);
}
//防抖函数
function debounce(fn,time) {
    
    
    let timer
    //使用闭包、定时器实现
    return function() {
    
    
        clearTimeout(timer)
        timer = setTimeout(() => {
    
    
            fn(1)
        },time)
    }
}

btn.addEventListener('click',debounce(getChange,2000))

</script>

2.节流
定义:在一段时间内,只会触发一次方法
场景:监听滚动事件;搜索框,搜索联想功能

 const btn = document.querySelector('button')
    function getChange(value) {
    
    
        console.log('点击了', value);
    }

//节流函数
    function throttle(fn, time) {
    
    
        let timer
        //使用闭包、定时器实现
        return function () {
    
    
            if (timer) {
    
    
                return
            }
            timer = setTimeout(() => {
    
    
                fn(1)
                timer = null
            }, time)

        }   
    }

    btn.addEventListener('click', throttle(getChange, 2000))

猜你喜欢

转载自blog.csdn.net/Hyanl/article/details/128135081