js事件节流

背景:在监听浏览器滚动条的scroll事件时该事件会触发很多次,这样当快速滚动时会有很差的性能,所以要限制事件触发的频率,可以防抖和节流,这里我记录简单的节流方法

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>事件节流</title>
  <style>
    .wrap {
      height: 10000px;
    }
  </style>
</head>

<body>
  <div class="wrap"></div>
  <script>
    var throttle = function (delay,interval, fn) {
      var startTime = new Date().getTime();
      var timer=null;
      return function () {
        var curTime = new Date().getTime();
        clearTimeout(timer);
        console.log(curTime - startTime, interval)
        if (curTime - startTime >= interval) {
          fn.apply(this, arguments)
          startTime = curTime
        }
        else{
          timer=setTimeout(fn,delay)
        }
      }
    }
    window.onscroll = throttle(500,2000, function () {
      console.log('我是水滴')
    })
  </script>
</body>

</html>

  上面判断如果此时距离上次触发达到了某个时间就立刻触发,否则就延迟多少毫秒再触发,这样当持续滚动时代码会在每次滚动结束后一段时间内触发一次,同时也会在时间间隔超过一段时间内执行一次。

原文地址:https://www.cnblogs.com/fantasy-zxf/p/8118871.html