码迷,mamicode.com
首页 > Web开发 > 详细

js防抖,节流

时间:2020-10-29 10:07:29      阅读:32      评论:0      收藏:0      [点我收藏+]

标签:art   ack   argument   span   wait   鼠标   cti   doctype   过程   

<!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>

 

js防抖,节流

标签:art   ack   argument   span   wait   鼠标   cti   doctype   过程   

原文地址:https://www.cnblogs.com/zjz666/p/13891738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!