js节流和防抖

节流:用于频繁请求操作例如change,click,保证某些代码不可以在没有间断的情况下连续重复执行,第一次调用,会创建一个定时器,在指定的时间间隔之后执行代码。当第二次调用时,它会清除前一次的定时器并设置新的一个,如果前一个定时器已经执行过了,这个操作就没有意义。然而,如果前一个定时器尚未执行,其实就是将其替换成一个新的定时器。目的是只有在执行函数的请求停止了一段时间之后执行。

//初级方案
let btn=document.querySelector('.btn')

    let timer=null
    btn.onclick=function(){
        clearTimeout(timer)
        timer=setTimeout(()=>{
            console.log('发起请求')
        },1000)
    }
//封装复用
let event = function (mouseEvent) {
            console.log('发起请求' + mouseEvent)
        }

        function throttle(event, time) {
            let timer = null
            return function (...args) {
                clearTimeout(timer)
                timer = setTimeout(() => {
                    event.apply(this, args)
                }, time)
            };
        }
        btn.addEventListener('click', throttle(event, 1000))
//优化
 btn.onclick = (function () {
            let timer = null
            return function(mouseEvent){
            clearTimeout(timer)
            timer = setTimeout(() => {
                console.log('发起请求')
            }, 1000)
            }
        })()

防抖:对于高密度操作例如resize,scroll,不管事件触发频率多高,都保证按一定的时间间隔应答

//初级方案
let flag = true
        window.onscroll = function () {
            if (flag) {
                flag = false
                setTimeout(() => {
                    console.log('刷新')
                    flag = true
                }, 3000)
            }
        }
 //优化
window.onscroll = (function () {
            let flag = true
            return function () {
                if (flag) {
                    flag = false
                    setTimeout(() => {
                        console.log('刷新')
                        flag = true
                    }, 3000)
                }
            }
        })()
 
原文地址:https://www.cnblogs.com/shirleysblog/p/13334123.html