防抖和节流

218 阅读1分钟

防抖

在连续触发某个函数时 直到最后才让对应的函数执行

 var timer = null;
    window.onscroll = function () {
        clearInterval(timer)
        timer = setTimeout(() => {
            console.log(666)
        }, 1000);
    }

封装成一个函数

function debounce(fn,wait) {
        wait = wait||100;
        var timer = null;
        return function () {
            clearInterval(timer)
            timer = setTimeout(() => {
                fn.apply(this,arguments)//保证this指向 和参数传递
            }, wait);
        }
    }
    let f = debounce(function () {
        console.log(666)
    })
    window.onscroll = f;

节流

节流 在连续触发某个函数的时候,每隔一段时间就触发一次该函数

function throttle(fn,wait=1000) {
        var flag = true;
        return function () {
            if (!flag) return;
            flag = false;
            setTimeout(() => {
                fn.apply(this, arguments);
                flag = true;
            }, wait);
        }
    }
    var f = function () {
        console.log(666)
    };
    window.onscroll = throttle(f)