節(jié)流和防抖

  • 你是不是遇到過提交按鈕,點擊多次發(fā)生多次提交的困惑?
  • 是不是遇到過下拉搜索框每按一次鍵盤就請求一次接口,scroll、resize事件頻繁執(zhí)行的困惑?

使用 節(jié)流和防抖 就可以解決此類問題

節(jié)流

原理:初次觸發(fā)時,立即執(zhí)行事件,n秒后才能再次執(zhí)行,n秒之內(nèi)觸發(fā)無效
應(yīng)用:主要解決 按鈕重復(fù)點擊 問題
代碼實現(xiàn)

function throttle(func,time) {
            let ifCanClick = true;
            return function () {
                if (ifCanClick) {
                    func.apply(this, arguments); // 執(zhí)行 并透傳this和參數(shù)
                    ifCanClick = false;
                    let setTime = setTimeout(function () {
                        ifCanClick = true;
                        clearTimeout(setTime);
                    }, time);
                }
            };    
  }
// 按鈕 綁定 節(jié)流
let twoDiv = document.getElementsByClassName('stop-dou')[0];
twoDiv.onclick = throttle( function (e) {
      console.log('有效點擊,去執(zhí)行');
      // 邏輯代碼
 }, 3000);

防抖

原理:初次觸發(fā)事件,n秒后延遲執(zhí)行,沒觸發(fā)一次就重新計時
應(yīng)用:下拉搜索input框,scroll,resize,防止頁面卡頓
代碼實現(xiàn)

function debounce (func, time) {
            let setTime = null
            return function () {
                console.log(5555)
                let _this = this;
                let _arguments = arguments;
                clearTimeout(setTime);
                setTime = setTimeout(function () {
                    func.apply(_this, _arguments);
                }, time);
            }
}
// 綁定 防抖 事件
let myInput = document.querySelector('.input-text');
            myInput.onkeydown = debounce(function(e) {
                console.log('開始執(zhí)行一次')
                let text = e.target.value;
                let showTag = document.querySelector('#showTag');
                showTag.textContent = text;
 }, 500)

使用 lodash.js 插件庫實現(xiàn)節(jié)流和防抖

import _ from lodash.js
_.throttle(function() { // 節(jié)流函數(shù)
   // 邏輯代碼
}, 3000)
_.debounce(function() { // 防抖函數(shù)
   // 邏輯代碼
}, 3000)

注意:函數(shù)參數(shù)不能用箭頭函數(shù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容