JS [笔记] debounce、throttle

完全参考,此处为整理笔记
[有趣面试题] 网页效能问题改善之 Debounce & Throttle
Debounce & Throttle — 那些前端开发应该要知道的小事(一)

适用情境

只要是使用者会在短时间内频繁触发多次事件处理器,例如:
autocomplete、滑鼠移动、改变视窗大小都可以适用此篇。因为你的浏览器会不断重新计算造成页面很缓慢

如Vue的computed因内部变数变动,致重复触发,此时可使用debounce设定触发时间,节省效能

<input type="text" id="debounce-input" placeholder="type something" />
<input type="text" id="throttle-input" placeholder="type something" />

debounce

所谓 Debounce,是让使用者在触发相同事件(如卷轴)的情境下,停止触发绑定事件的效果,直到使用者停止触发相同事件。

因为使用者输入一次你就要 filter 一次,假如使用者频繁输入就可能会影响到效能
设一个 timeout,例如输入以後过两秒才去抓一次使用者输入值
好处就是可以防止 js 频繁去筛选资料,等待两秒後再一次筛选就好

    // func: 要执行的 function
    // delay: 延迟几秒才执行
    function debounce(func, delay) {
      // timeout 初始值
      let timeout = null;
      return function () {
        let context = this; // 指向 myDebounce 这个 input
        let args = arguments; // KeyboardEvent
        clearTimeout(timeout);

        timeout = setTimeout(function () {
          func.apply(context, args);
        }, delay);
      };
    }
    // 1 2秒後执行
    // 2 前一个清掉,2秒後执行 1 2
    // 3 前一个清掉,2秒後执行 1 2 3
    
    let myDebounce = document.getElementById("debounce-input");
    // myDebounce.addEventListener('keyup', function(e){
    //         console.log(e.target.value)
    // })
    
    myDebounce.addEventListener(
      "keyup",
      debounce(function (e) {
        console.log(e.target.value);
      }, 2000)
    );

throttle

为使用者触发相同事件时提供间隔,控制特定时间内事件触发的次数。
它防止一下输入太频繁的值,所以会限制一个时间,在这时间内触发的值会被存到下一次再存

    function throttle(func, delay) {
      let inThrottle;
      let timeout = null;
      return function () {
        let context = this;
        let args = arguments;
        if (!inThrottle) {
          // 输入之後两秒内都不回进入这边
          func.apply(context, args);
          inThrottle = true;
          clearTimeout(timeout);
          timeout = setTimeout(function () {
            inThrottle = false;
          }, delay);
        }
      };
    }
    
    document.getElementById("throttle-input").addEventListener(
      "keyup",
      throttle(function (e) {
        console.log(e.target.value);
      }, 2000)
    );

<<:  纯JS实作照片上传、下载与预览

>>:  .NET 前後分离 Web API 蓝新金流串接

【Day07】记忆体存放与释放

在 Day04 有提到在 JavaScript 里, 函式执行时会产生函式执行环境,在该执行环境中会...

登录档结构和物理位置--一颗四处散落的tree

在上一篇我们了解登录档的意义和由来後,这里要开始解说他的形式了 再次提醒,没有十足的把握请勿做新增修...

企划实现(30)

止损 止损顾名思义就是停止损失,今天在做企划的同时,世界并不会停下来等你发展,所以如果在做企划的同时...

Android x Kotlin : 简易实作第一堂-自定义customView与在xml中设定属性预设值

简介 在一个专案中,有时候会有一组view在很多地方都会用到,在每个地方都重刻一遍会很麻烦。这时候可...

Engineering, Life Cycle Stages, and Processes

Engineering, Life Cycle Stages, and Processes Eng...