小白圖解防抖動與節流-Javascript篇

防抖動與節流

點擊查看 源碼

防抖動

var debounce = function (fn, delay, isImmediate) {
    var timer = null;
    // 默認不當即觸發
    isImmediate = typeof isImmediate === "undefined" ? false : isImmediate;

    return function () {
        var ctx = this, // 保存做用域
            args = arguments; // 保存參數
        // 初始化清空全部定時器
        if (timer) {
            clearTimeout(timer);
        }
        // 若是是當即觸發
        if (isImmediate) {
            if (!timer) { // timer爲空時觸發操做
                fn.apply(ctx, args);
            }
            // delay時間後置空timer
            timer = setTimeout(_ => {
                timer = null;
            }, delay);
        } else { // delay時間後觸發操做
            timer = setTimeout(_ => {
                fn.apply(ctx, args);
            }, delay);
        }
    };
};

防抖動當即觸發
debounce-immediate.pnggit

防抖動
debounce.pnggithub

節流

var throttle = function (fn, delay, isImmediate) {
    var timer = null;
    // 默認當即觸發
    isImmediate = typeof isImmediate === "undefined" ? true : isImmediate;

    return function () {
        var ctx = this, // 保存做用域
            args = arguments; // 保存參數
        if (!timer) { // timer爲空時
            if (isImmediate) fn.apply(ctx, args); // 當即觸發
            timer = setTimeout(function () {
                clearTimeout(timer);
                timer = null;
                if (!isImmediate) fn.apply(ctx, args); // delay時間後觸發操做
            }, delay);
        }
    };
};

節流當即觸發
throttle-immediate.png
節流
throttle.pngapp

總結

  • 防抖動:將多個操做合併爲一個操做(例如,鍵盤輸入關鍵字搜索內容),在規定延時時間後觸發,若是在定時器時間範圍內觸發,則會清楚定時器,從新計時
  • 節流:在給定的延時時間後觸發一次操做,在此時間範圍內的操做均不觸發(例如,圖片懶加載、向下無限滾動獲取新數據)
相關文章
相關標籤/搜索