防抖和節流

防抖和節流的區別:防抖是將屢次執行變爲最後一次執行,節流是將屢次執行變爲每隔一段時間執行html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>防抖、節流</title>
</head>
<body>
  <input type="text" id="input">
  <button id="button">提交</button>
</body>
</html>

<script>

  // 防抖 - 定時器
  function debounce(fn, wait) {
    var timer = null
    return function() {
      if(timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => { fn.call(this, this.value) }, wait)
    }
  }
  function checked(value) {
    console.log(value)
  }
  document.getElementById('input').addEventListener('input', debounce(checked, 1000))


  // 節流 - 時間戳
  // function throttle(fn, wait) {
  //   var prev = Date.now()
  //   return function() {
  //     var now = Date.now()
  //     if (now - prev > wait) {
  //       fn()
  //       prev = Date.now() 
  //     }
  //   }
  // }
  
  // 節流 - 定時器
  function throttle(fn, wait) {
    var timer = null
    return function() {
      if (!timer) {
        timer = setTimeout(() => {
          timer = null
          fn()
        }, wait)
      }
    }
  }
  function btnClick() {
    console.log('submit')
  }
  document.getElementById('button').addEventListener('click', throttle(btnClick, 1000))
</script>

參考
https://www.jianshu.com/p/c8b...
https://www.cnblogs.com/youma...this

相關文章
相關標籤/搜索