防抖和節流

防抖

在連續觸發某個函數時 直到最後才讓對應的函數執行bash

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;
複製代碼

節流

節流 在連續觸發某個函數的時候,每隔一段時間就觸發一次該函數app

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)
複製代碼
相關文章
相關標籤/搜索