js节流demo

代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>节流(时间戳 + 定时器)</title>
  <style>
    body {
      margin: 0;
    }
    .scroll-wrapper {
      width: 240px;
      height: 300px;
      overflow-y: scroll;
      -webkit-overflow-scrolling: touch;
    }
    .content {
      width: 100%;
      height: 5000px;
      background: linear-gradient(to bottom, #ff5454, #ccff65, #4dffaf, #507aff, #ef4bff);
    }
    p {
      margin: 10px 0;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <p>上下滑动渐变色块,查看下方打印结果</p>
  <p>提示:持续滑动不要停</p>
  <div class="scroll-wrapper" id="scroll-wrapper">
    <div class="content"></div>
  </div>
  <div id="result"></div>
  <script>
    // 方法1:时间戳
    function throttle1 (fn, delay) {
      let prev = Date.now()
      return function () {
        let that = this
        let now = Date.now()
        if (now - prev >= delay) {
          fn()
          prev = Date.now()
        }
      }
    }
    // 方法2:定时器
    function throttle2 (fn, delay) {
      let timer = null
      return () => {
        if (!timer) {
          timer = setTimeout(() => {
            fn()
            timer = null
          }, delay)
        }
      }
    }
    function handleScroll () {
      let result = document.getElementById('result')
      let p = document.createElement('p')
      p.innerText = '滑动过程中我一秒钟才执行一次'
      result.append(p)
    }
    let wrapper = document.getElementById('scroll-wrapper')
    wrapper.addEventListener('scroll', throttle1(handleScroll, 1000))
    // wrapper.addEventListener('scroll', throttle2(handleScroll, 1000))
  </script>
</body>
</html>

@throttle.html

3+

效果:

Scroll Up