setTimeout()
เป็นหนึ่งใน Timing Events Window Object อนุญาตให้รันโค้ดที่ช่วงเวลาที่ระบุ Object นี้มี setTimeout() สำหรับรันฟังก์ชันหลังจากเวลาที่กำหนด รับ 2 พารามิเตอร์ คือ ฟังก์ชัน และ เวลา (มิลลิวินาที) ที่ระบุช่วงเวลาก่อนรันฟังก์ชัน
Syntax
window.setTimeout(function, milliseconds);
ตัวอย่างที่ 1
ในตัวอย่างนี้ เวลาที่ส่งให้ setTimeout() คือ 2 วินาที ฟังก์ชันจะรันหลัง 2 วินาที และแสดง Output
<html> <body> <p>wait 2 seconds.</p> <script> setTimeout(function(){ document.write("Tutorix is the best e-learning platform"); }, 2000); </script> </body> </html>
ผลลัพธ์
wait 2 seconds Tutorix is the best e-learning platform
ตัวอย่างที่ 2
ในตัวอย่างนี้ เวลาที่ส่งคือ 3 วินาที ฟังก์ชันรันหลัง 3 วินาที และแสดง Output
<html> <body> <p id = "time"></p> <script> setTimeout(function(){ document.getElementById("time").innerHTML = "Tutorix is the product of Tutorialspoint"; }, 3000); </script> </body> </html>
ผลลัพธ์
Tutorix is the product of Tutorialspoint.