คุณสามารถสร้าง Countdown Timer ใน JavaScript โดยใช้เมธอด setInterval เมธอด setInterval() จะเรียกฟังก์ชันหรือรันโค้ดซ้ำๆ ด้วยเวลาล่าช้าคงที่ระหว่างแต่ละครั้ง
เพื่อสร้าง Countdown เราต้องตรวจสอบความต่างระหว่างเวลาปัจจุบันและเวลาสุดท้าย และอัปเดต Countdown ตลอดเวลา ตัวอย่างเช่น
ตัวอย่าง
let countDownDate = new Date("Jul 21, 2020 00:00:00").getTime(); let x = setInterval(() => { let now = new Date().getTime(); let distance = countDownDate - now; // คำนวณเวลาเป็นวัน ชั่วโมง นาที วินาที let days = Math.floor(distance / (1000 * 60 * 60 * 24)); let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); let seconds = Math.floor((distance % (1000 * 60)) / 1000); console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s"); // ถ้า Countdown จบ ให้เขียนข้อความ if (distance < 0) { clearInterval(x); console.log("completed") } }, 1000);ผลลัพธ์
จะได้ผลลัพธ์ดังนี้
310d 0h 6m 46s 310d 0h 6m 45s 310d 0h 6m 44s 310d 0h 6m 43s 310d 0h 6m 42s 310d 0h 6m 41s 310d 0h 6m 40s 310d 0h 6m 39s 310d 0h 6m 38s 310d 0h 6m 37s 310d 0h 6m 36s 310d 0h 6m 35s 310d 0h 6m 34s 310d 0h 6m 33s