节流的基本实现

22 阅读1分钟

Throttle节流是一种优化性能技术,通过控制在一定的时间间隔内只执行一次函数,来限制事件的触发次数。它确保在一个时间段内,事件处理函数被执行的最大频率为指定的间隔时间。

节流的基本实现

function throttle(fn, interval, options = { leading: true } ) {
  let lastTime = 0
  const { leading } = options

  return function (...args) {
    // nowTime是当前时间的时间戳
    const nowTime = new Date().getTime()

    // 取消第一次的响应函数
    if (!leading && !lastTime) {
      lastTime = nowTime
    }

    // 刚开始一定是小于0,符合条件,所以第一次会触发
    const remainTime = interval - (nowTime - lastTime) 
    if (remainTime <= 0) {
      fn.apply(this, args)
      lastTime = nowTime
    }
  }

}

测试用例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text">

    <script src="./throttle.js"></script>
    <script>
        const inputEl = document.querySelector('input')
        let count = 0

        const changeInput = function (event) {
            console.log(`触发了${++count}次方法`, this, event);
        }
        const _throttle = throttle(changeInput, 2000, false)

        inputEl.oninput = _throttle
    </script>
</body>
</html>