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

Cách trì hoãn gọi hàm trong JavaScript (setTimeout)

Cú pháp

setTimeout(callback, delayMs, arg1, arg2, ...);
  • callback: hàm sẽ thực thi sau độ trễ.
  • delayMs: mili-giây (1000 = 1 giây).
  • arg1, arg2...: đối số truyền cho callback (không hỗ trợ IE cũ).

Ví dụ cơ bản

<!DOCTYPE html>
<html>
<body>
  <button onclick="delayAlert()">Thử sau 5 giây</button>
  <script>
    function delayAlert() {
      setTimeout(function() {
        alert("Đã 5 giây!");
      }, 5000);
    }
  </script>
</body>
</html>

Ví dụ với tham số

function greet(name, age) {
  console.log("Xin chào " + name + ", " + age + " tuổi");
}

setTimeout(greet, 2000, "An", 25); // sau 2s in: "Xin chào An, 25 tuổi"

Hủy timeout

var timerId = setTimeout(myFunc, 3000);
clearTimeout(timerId); // hủy nếu chưa chạy

Lưu ý

  • setTimeout không chính xác tuyệt đối (tối thiểu ~4ms trong tab nền).
  • Dùng setInterval cho lặp lại định kỳ.
  • Arrow function giữ this lexical: setTimeout(() => this.method(), 1000).