JavaScript 节流学习

218 阅读1分钟

原理: 如果一直持续触发某个方法,只会在规定时间触发一次 应用场景: 页面滚动事件 实现方式: 时间戳, 设定定时器 html还是之前的

<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
  <title>debounce</title>
  <style>
    #content {
      text-align: center;
      font-size: 30px;
    }
  </style>
</head>

<body>
  <div id="content"></div>
</body>
<script src="./debounce"></script>
</html>

时间戳方式

 function throttle(fn, wait) {
    let preTime = 0
    return function () {
      let nowTime = new Date()
      let args = arguments;
      let ctx = this
      if (nowTime - preTime > wait) {
        fn.apply(ctx, args)
        preTime = nowTime
      }
    }
  }

定时器方式

 function throttle(fn, wait) {
    let timeOut
    return function (params) {
      let ctx = this
      let args = arguments
      if (!timeOut) {
        timeOut = setTimeout(() => {
          fn.apply(ctx, args)
          timeOut = null
        }, wait)
      }
    }
  }