欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript專題之underscore防抖實例學(xué)習(xí)

 更新時間:2022年09月20日 11:28:37   作者:冴羽  
這篇文章主要為大家介紹了JavaScript專題之underscore防抖實例學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

JavaScript 專題系列第一篇,講解防抖,帶你從零實現(xiàn)一個 underscore 的 debounce 函數(shù)

前言

在前端開發(fā)中會遇到一些頻繁的事件觸發(fā),比如:

  • window 的 resize、scroll
  • mousedown、mousemove
  • keyup、keydown
    ……

為此,我們舉個示例代碼來了解事件如何頻繁的觸發(fā):

我們寫個 index.html 文件:

<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
    <title>debounce</title>
    <style>
        #container{
            width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px;
        }
    </style>
</head>
<body>
    <div id="container"></div>
    <script src="debounce.js"></script>
</body>
</html>

debounce.js 文件的代碼如下:

var count = 1;
var container = document.getElementById('container');
function getUserAction() {
    container.innerHTML = count++;
};
container.onmousemove = getUserAction;

我們來看看效果:

debounce

從左邊滑到右邊就觸發(fā)了 165 次 getUserAction 函數(shù)!

因為這個例子很簡單,所以瀏覽器完全反應(yīng)的過來,可是如果是復(fù)雜的回調(diào)函數(shù)或是 ajax 請求呢?假設(shè) 1 秒觸發(fā)了 60 次,每個回調(diào)就必須在 1000 / 60 = 16.67ms 內(nèi)完成,否則就會有卡頓出現(xiàn)。

為了解決這個問題,一般有兩種解決方案:

  • debounce 防抖
  • throttle 節(jié)流

防抖

今天重點講講防抖的實現(xiàn)。

防抖的原理就是:你盡管觸發(fā)事件,但是我一定在事件觸發(fā) n 秒后才執(zhí)行,如果你在一個事件觸發(fā)的 n 秒內(nèi)又觸發(fā)了這個事件,那我就以新的事件的時間為準(zhǔn),n 秒后才執(zhí)行,總之,就是要等你觸發(fā)完事件 n 秒內(nèi)不再觸發(fā)事件,我才執(zhí)行,真是任性吶!

第一版

根據(jù)這段表述,我們可以寫第一版的代碼:

// 第一版
function debounce(func, wait) {
    var timeout;
    return function () {
        clearTimeout(timeout)
        timeout = setTimeout(func, wait);
    }
}

如果我們要使用它,以最一開始的例子為例:

container.onmousemove = debounce(getUserAction, 1000);

現(xiàn)在隨你怎么移動,反正你移動完 1000ms 內(nèi)不再觸發(fā),我再執(zhí)行事件。

頓時就從 165 次降低成了 1 次!

棒棒噠,我們接著完善它。

this

如果我們在 getUserAction 函數(shù)中 console.log(this),在不使用 debounce 函數(shù)的時候,this 的值為:

<div id="container"></div>

但是如果使用我們的 debounce 函數(shù),this 就會指向 Window 對象!

所以我們需要將 this 指向正確的對象。

我們修改下代碼:

// 第二版
function debounce(func, wait) {
    var timeout;
    return function () {
        var context = this;
        clearTimeout(timeout)
        timeout = setTimeout(function(){
            func.apply(context)
        }, wait);
    }
}

現(xiàn)在 this 已經(jīng)可以正確指向了。讓我們看下個問題:

event 對象

JavaScript 在事件處理函數(shù)中會提供事件對象 event,我們修改下 getUserAction 函數(shù):

function getUserAction(e) {
    console.log(e);
    container.innerHTML = count++;
};

如果我們不使用 debouce 函數(shù),這里會打印 MouseEvent 對象,如圖所示:

MouseEvent

但是在我們實現(xiàn)的 debounce 函數(shù)中,卻只會打印 undefined!

所以我們再修改一下代碼:

// 第三版
function debounce(func, wait) {
    var timeout;
    return function () {
        var context = this;
        var args = arguments;
        clearTimeout(timeout)
        timeout = setTimeout(function(){
            func.apply(context, args)
        }, wait);
    }
}

返回值

再注意一個小點,getUserAction 函數(shù)可能是有返回值的,所以我們也要返回函數(shù)的執(zhí)行結(jié)果

// 第四版
function debounce(func, wait) {
    var timeout, result;
    return function () {
        var context = this;
        var args = arguments;
        clearTimeout(timeout)
        timeout = setTimeout(function(){
            result = func.apply(context, args)
        }, wait);
        return result;
    }
}

到此為止,我們修復(fù)了三個小問題:

  • this 指向
  • event 對象
  • 返回值

立刻執(zhí)行

這個時候,代碼已經(jīng)很是完善,但是為了讓這個函數(shù)更加完善,我們接下來思考一個新的需求。

這個需求就是:

我不希望非要等到事件停止觸發(fā)后才執(zhí)行,我希望立刻執(zhí)行函數(shù),然后等到停止觸發(fā)n秒后,才可以重新觸發(fā)執(zhí)行。

想想這個需求也是很有道理的嘛,那我們加個 immediate 參數(shù)判斷是否是立刻執(zhí)行。

// 第五版
function debounce(func, wait, immediate) {
    var timeout, result;
    return function () {
        var context = this;
        var args = arguments;
        if (timeout) clearTimeout(timeout);
        if (immediate) {
            // 如果已經(jīng)執(zhí)行過,不再執(zhí)行
            var callNow = !timeout;
            timeout = setTimeout(function(){
                timeout = null;
            }, wait)
            if (callNow) result = func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                result = func.apply(context, args)
            }, wait);
        }
        return result;
    }
}

取消

最后我們再思考一個小需求,我希望能取消 debounce 函數(shù),比如說我 debounce 的時間間隔是 10 秒鐘,immediate 為 true,這樣的話,我只有等 10 秒后才能重新觸發(fā)事件,現(xiàn)在我希望有一個按鈕,點擊后,取消防抖,這樣我再去觸發(fā),就可以又立刻執(zhí)行啦,是不是很開心?

為了這個需求,我們寫最后一版的代碼:

// 第六版
function debounce(func, wait, immediate) {
    var timeout, result;
    var debounced = function () {
        var context = this;
        var args = arguments;
        if (timeout) clearTimeout(timeout);
        if (immediate) {
            // 如果已經(jīng)執(zhí)行過,不再執(zhí)行
            var callNow = !timeout;
            timeout = setTimeout(function(){
                timeout = null;
            }, wait)
            if (callNow) result = func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                result = func.apply(context, args)
            }, wait);
        }
        return result;
    };
    debounced.cancel = function() {
        clearTimeout(timeout);
        timeout = null;
    };
    return debounced;
}

演示效果如下:

debounce-cancel

至此我們已經(jīng)完整實現(xiàn)了一個 underscore 中的 debounce 函數(shù),恭喜,撒花!

專題系列

JavaScript專題系列:http://www.dbjr.com.cn/list/list_3_1.htm

JavaScript專題系列預(yù)計寫二十篇左右,主要研究日常開發(fā)中一些功能點的實現(xiàn),比如防抖、節(jié)流、去重、類型判斷、拷貝、最值、扁平、柯里、遞歸、亂序、排序等,特點是研(chao)究(xi) underscore 和 jQuery 的實現(xiàn)方式。

以上就是JavaScript專題之underscore防抖實例學(xué)習(xí)的詳細(xì)內(nèi)容,更多關(guān)于JavaScript underscore防抖的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論