美文网首页
throttle & debounce 的差异

throttle & debounce 的差异

作者: 莫帆海氵 | 来源:发表于2021-03-15 20:30 被阅读0次

throttle

Throttling prevents a function from being called more than once in a given window of time.
节流可防止在给定的时间范围内多次调用某个函数。

节流是阻止函数在指定的时间段内执行超过一次。
用处:更在于基于时间频率的控制,比如1次/秒,1次/10秒

debounce

Debouncing ensures that a function will not be executed until after a certain amount of time has passed since it was last called.
防抖是确保直到上一次调用函数经过一定时间后,该函数才会执行

防抖是确保函数从上次执行经过一定时间后才执行。
用处:确保函数在延迟一段时间才执行,比如监听输入框的输入变化,只有输入停止超过指定时间才会执行,如果等待中间函数再次执行则会继续等待相同时间。

两者区别

区别再于如果函数一直调用,那 debounce 就不会触发,它会一直向后推迟,直到距离上一次执行超过指定时间才执行;而 throttle 是只要到了指定时间函数就可以执行。

一个例子:

<!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>Debounce & Throttle demo</title>
</head>
<body>
  <button id="btn">点击</button>
  <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
  <script type="text/javascript">
  window.addEventListener('load', () => {
    var btn = document.getElementById('btn')
    btn.addEventListener('click', handleClick)
    btn.addEventListener('click', clickWithThrottle)
    btn.addEventListener('click', clickWithDebounce)
  })

  var clickWithDebounce = _.debounce(handleDebounce, 500)
  var clickWithThrottle = _.throttle(handleThrottle, 500)

  var countForDebounce = 0
  var countForThrottle = 0
  var countForClick = 0
  function handleDebounce() {
    console.log('debounce click', countForDebounce)
    countForDebounce++
  }
  function handleThrottle() {
    console.log('throttle click', countForThrottle)
    countForThrottle++
  }
  function handleClick() {
    console.log('click', countForClick)
    countForClick++
  }
  </script>
</body>
</html>

不同频率的点击输出如下:

click 0
throttle click 0
debounce click 0
click 1
throttle click 1
click 2
throttle click 2
click 3
click 4
throttle click 3
debounce click 1

在线的例子 http://demo.nimius.net/debounce_throttle/

10_1.png

相关文章

网友评论

      本文标题:throttle & debounce 的差异

      本文链接:https://www.haomeiwen.com/subject/lcfkcltx.html