倒計時如何用js代碼寫

倒計時可以通過JavaScript的`setTimeout`函數(shù)來實現(xiàn)。以下是一個簡單的倒計時示例,它會計算當前時間到指定時間之間的差值,并每秒更新一次顯示。假設我們要...
倒計時可以通過JavaScript的`setTimeout`函數(shù)來實現(xiàn)。以下是一個簡單的倒計時示例,它會計算當前時間到指定時間之間的差值,并每秒更新一次顯示。
假設我們要創(chuàng)建一個從當前時間開始,倒計時到2023年1月1日0點的倒計時。
```javascript
// 設置倒計時結束的時間
const endTime = new Date('2023-01-01T00:00:00').getTime();
// 更新倒計時的函數(shù)
function updateCountdown() {
// 獲取當前時間
const now = new Date().getTime();
// 計算時間差
const timeDiff = endTime now;
// 計算天數(shù)、小時數(shù)、分鐘數(shù)和秒數(shù)
const days = Math.floor(timeDiff / (1000 60 60 24));
const hours = Math.floor((timeDiff % (1000 60 60 24)) / (1000 60 60));
const minutes = Math.floor((timeDiff % (1000 60 60)) / (1000 60));
const seconds = Math.floor((timeDiff % (1000 60)) / 1000);
// 輸出到HTML元素
document.getElementById('countdown').innerHTML = days + "天 " + hours + "小時 "
+ minutes + "分鐘 " + seconds + "秒 ";
// 如果倒計時結束,則顯示結束信息
if (timeDiff < 0) {
clearInterval(interval);
document.getElementById('countdown').innerHTML = "倒計時結束";
本文鏈接:http:///bian/397477.html
上一篇:東莞國家開放大學要多少學費