หากต้องการชะลอการเรียกใช้ฟังก์ชัน ให้ใช้ฟังก์ชัน setTimeout()
setTimeout(functionname, milliseconds, arg1, arg2, arg3...)
ต่อไปนี้เป็นพารามิเตอร์ -
ชื่อฟังก์ชัน − ชื่อฟังก์ชันสำหรับฟังก์ชันที่จะดำเนินการ
มิลลิวินาที − จำนวนมิลลิวินาที
arg1, arg2, arg3 − นี่คืออาร์กิวเมนต์ที่ส่งผ่านไปยังฟังก์ชัน
ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อชะลอการเรียกใช้ฟังก์ชัน JavaScript ด้วยการเรียกกลับ setTimeout()
<!DOCTYPE html>
<html>
<body>
<button onclick="timeFunction()">Submit</button>
<script>
function timeFunction() {
setTimeout(function(){ alert("After 5 seconds!"); }, 5000);
}
</script>
<p>Click the above button and wait for 5 seconds.</p>
</body>
</html>