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>
  • 相关阅读:
    hdu 1269 迷宫城堡(trajan判环)
    codeforces 591 E. Three States(bfs+思维)
    PowerDesigner 教程
    SQL中inner join、outer join和cross join的区别
    SQL 报表 --简易进销系统
    SQL PROMPT5.3.4.1的一些设置选项
    SQL锁机制和事务隔离级别
    洛谷P1901 发射站
    洛谷P1823 [COI2007] Patrik 音乐会的等待
    洛谷P2947 [USACO09MAR]向右看齐Look Up
  • 原文地址:https://www.cnblogs.com/zjz666/p/13891738.html
Copyright © 2011-2022 走看看