Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kích hoạt hàm JS khi người dùng ngừng gõ (thay vì on keyup)

Để kích hoạt hàm khi người dùng ngừng gõ (debounce), dùng setTimeout + clearTimeout:

Ví dụ

<html>
  <body>
    <script>
      var timer = null;
      $("#myText").keydown(function() {
        clearTimeout(timer);
        timer = setTimeout(doStuff, 1000);
      });
      function doStuff() {
        alert("Viết thêm đi!");
      }
    </script>
    <input type="text" id="myText" />
  </body>
</html>

Giải thích: Mỗi lần nhấn phím, reset timer. Chỉ khi ngừng gõ 1 giây (1000ms) thì doStuff mới chạy. Kỹ thuật này gọi là debouncing.

Cải tiến hiện đại: Dùng input event thay keydown (bắt paste, autocomplete), và requestAnimationFrame hoặc thư viện lodash.debounce.