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

Phương thức setTimeout() trong JavaScript

setTimeout()

Một trong các timing events. Object window cho phép thực thi code sau một khoảng thời gian. setTimeout() chạy function một lần sau khoảng thời gian chỉ định. Nhận 2 tham số: function và thời gian (milliseconds).

Cú pháp

window.setTimeout(function, milliseconds);

Ví dụ 1: Chạy sau 2 giây

<html> <body> <p>wait 2 seconds.</p> <script>    setTimeout(function(){       document.write("Tutorix is the best e-learning platform");    }, 2000); </script> </body> </html>

Kết quả

wait 2 seconds Tutorix is the best e-learning platform

Ví dụ 2: Cập nhật DOM sau 3 giây

<html> <body> <p id = "time"></p> <script> setTimeout(function(){ document.getElementById("time").innerHTML = "Tutorix is the product of Tutorialspoint"; }, 3000); </script> </body> </html>

Kết quả

Tutorix is the product of Tutorialspoint.

Lưu ý:

  • Trả về timeout ID để dùng clearTimeout() hủy
  • Chỉ chạy một lần (khác setInterval lặp lại)
  • Tham số thứ 3+ truyền vào function callback
  • Trong Node.js: setTimeout trả về object Timer, không phải số