zoukankan      html  css  js  c++  java
  • 防抖和节流

    防抖和节流

    两者都是在一段时间内连续触发同一事件而为了避免事件处理函数频繁连续的调用而采取的解决方案。

    防抖就是合并一段时间内连续的触发的事件

    而节流控制相同事件之间必须要具有一定的时间间隔

    打个比方,假如同一事件在10秒内触发了N次,如果采用防抖的方案,那么事件处理函数在10秒内只会触发一次。而如果采用节流的方案,可能就是在每间隔1秒的地方触发一次。

    防抖的代码:

    function debounce(fn, wait) {
      let timer = null;
      
      return (...argms) => {
        if (timer !== null) {
          clearTimeout(timer);
        }
    
        timer = setTimeout(() => fn(...argms), wait);
      };
    }
    

    节流:

    function throttle(fn, delay) {
      let pre = null;
    
      return (...argms) => {
        const now = Date.now();
        const temp = pre;
        pre = now;
    
        if (temp === null || now - temp >= delay) {
          fn(...argms);
        }
      };
    };
    
  • 相关阅读:
    TinyOS功率编程指南
    深度学习入门资料
    通信常识
    CTF入门
    前端开发工具之服务器选择
    Spring
    NoSQL -- MongoDB
    NoSQL -- Redis
    mysql alter table修改表结构添加多个字段的几个写法
    gongle 访问助手安装
  • 原文地址:https://www.cnblogs.com/freesfu/p/14671704.html
Copyright © 2011-2022 走看看