首页 > 其他 > 详细

防抖节流

时间:2020-05-15 15:19:01      阅读:58      评论:0      收藏:0      [点我收藏+]

防抖(debounce):所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

节流(throttle):所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。

 防抖在于控制次数,节流在于控制频率!

<!DOCTYPE html>

<body>
  <div id="content"></div>
</body>

<style>
  #content {
    width: 500px;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ccc;
    margin: 200px auto;
    font-size: 28px;
  }
</style>
<script>
  let num = 1;
  let content = document.getElementById("content")

  function count() {
    content.innerHTML = num++;
  }

  //防抖 immediate true 表立即执行,false 表非立即执行
  function debounce(fn, wait, immediate) {
    let timer;
    return function () {
      let _self = this;
      let args = arguments;
      if (timer) clearTimeout(timer);
      if (immediate) {
        let callNow = !timer;
        timer = setTimeout(() => {
          timer = null;
        }, wait);
        if (callNow) fn.apply(_self, args)
      } else {
        timer = setTimeout(() => {
          fn.apply(_self, args)
        }, wait)
      }

    }
  }
  //节流 type为1是时间戳比较  type为2是定时器
  function throttle(fn, wait, type) {
    if (type == 1) {
      var c = 0;
    } else {
      var timer;
    }
    return function () {
      let _self = this;
      let args = arguments;
      if (type == 1) {
        let now = Date.now();
        if (now - c > wait) {
          fn.apply(_self, args)
          c = now;
        }
      } else {
        if (!timer) {
          timer = setTimeout(() => {
            timer = null;
            fn.apply(_self, args)
          }, wait)
        }
      }
    }
  }

  content.onmousemove = throttle(count, 1000, 2)


</script>

 

防抖节流

原文:https://www.cnblogs.com/returnvalue/p/12894892.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!