js节流

66 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      height: 5000px;
    }
  </style>
</head>
<body>
  <button id="btn">点击</button>
  <br />
  <br />
  <br />
  <br />
  <br />
  参考文档:https://www.bilibili.com/video/BV1vo4y1y7tD?p=18
  <script>
    // 实现了有头有尾, 刚进来执行一次,隔一段时间执行一次
    const { log } = console
    const scrollFn = function (ev) {
      log(3)
    }
    window.onscroll = myThrottle(scrollFn, 300)
    
    function myThrottle(fn, wait) {
      if (typeof fn !== 'function') throw new Error('fn is not an function') 
      if (typeof wait === 'undefined') wait = 300

      let previous = 0
      let timer = null
      return function (...args) {
        let now = new Date()
        let self = this
        let interval = wait - (now - previous)
        if (interval <= 0) {
          timer = null // 解决碰巧非高频的滚动(情况一interval <= 0)和setTimeout延迟执行(情况二 !timer)碰到一起时
          // 非高频操作
          fn.apply(self, args)
          previous = new Date()
        } else if (!timer){ // 判断是不是第一次操作
          timer = setTimeout(() => {
            timer = null // timer置为null是为了解决隔一段时间后重新快速滚动时程序能进入判断条件(!tiemr)中
            fn.apply(self, args)
            previous = new Date()
          }, interval)
        }
      }
    }
  </script>
</body>
</html>