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

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <style>
        div {
          height: 150px;
          line-height: 150px;
          text-align: center;
          color: #fff;
          background-color: #ccc;
          font-size: 80px;
        }
    
        h2 {
          margin: 10px 0;
        }
    
        p {
          color: #666;
          margin: 0;
        }
      </style>
    </head>
    
    <body>
      <p>说明:鼠标在以下元素不断移动,将会不断执行一个数值累加事件,但中间分别加入了防抖和节流函数。</p>
    
      <h2>防抖</h2>
      <p>在鼠标停止移动后300ms执行一次数值累加事件。</p>
      <div id="content">0</div>
      <h2>节流</h2>
      <p>在鼠标移动过程中,每300ms执行一次数值累加事件。</p>
      <div id="content2">0</div>
    </body>
    
    </html>
    <script>
      // 防抖函数
      function debounce(func, wait) {
        let timeout = null;
        return function () {
          let context = this;
          let args = arguments;
          if (timeout) clearTimeout(timeout);
          timeout = setTimeout(() => {
            func.apply(context, args)
          }, wait);
        }
      }
    
      // test debounce
      let num = 1;
      let content = document.getElementById('content');
    
      function count() {
        content.innerHTML = num++;
      };
      content.onmousemove = debounce(count, 300);
    
    
    
      // 节流函数
      function throttle(func, wait) {
        let timeout = null;
        return function () {
          let context = this;
          let args = arguments;
          if (!timeout) {
            timeout = setTimeout(() => {
              timeout = null;
              func.apply(context, args)
            }, wait)
          }
        }
      }
    
      // test throttle
      let num2 = 1;
      let content2 = document.getElementById('content2');
    
      function count2() {
        content2.innerHTML = num2++;
      };
      content2.onmousemove = throttle(count2, 300);
    </script>
  • 相关阅读:
    VS注释提示英文变中文的方法
    Windows 10安裝.net Framework 3.5出現0X800F0954錯誤
    NodeJS+NPM+Bower+Android环境安装配置
    复合索引
    高并发的核心技术-幂等的实现方案
    Redis初使用
    数据库SQL查找包含某列的所有table
    多线程中的wait与sleep到底谁释放了锁
    https配置
    iOS下的实际网络连接状态检测(转)
  • 原文地址:https://www.cnblogs.com/zjz666/p/13891738.html
Copyright © 2011-2022 走看看