防抖

<!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>
    <h1>防抖</h1>
    <input type="text" id="ipt" />
  </body>
  <script>
    const inputDom = document.getElementById('ipt')

    function debounce(fn) {
      let timer = null
      return function (val) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn(val)
        }, 300)
      }
    }

    inputDom.addEventListener(
      'input',
      debounce(e => {
        console.log('发送网络请求', e.target.value)
      })
    )
  </script>
</html>

 

上一篇:Linux定时器和时间管理


下一篇:C#中重写(override)和覆盖(new)的区别