首次上傳:2021/05/10
29 - Countdown Timer
主題
製作一個倒數計時器。
步驟
Step1. 取得頁面元素並替預設
1 2 3
| const timerDisplay = document.querySelector('.display__time-left'); const endTime = document.querySelector('.display__end-time'); const buttons = document.querySelectorAll('[data-time]');
|
Step2. 設定計時器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| let countdown;
function timer(seconds) { clearInterval(countdown); const now = Date.now(); const timeStamp = now + seconds * 1000; displayTimeLeft(seconds); displayEndTime(timeStamp); countdown = setInterval(() => { const secondsLeft = Math.round((timeStamp - Date.now()) / 1000); if(secondsLeft < 0) { clearInterval(countdown); return; } displayTimeLeft(secondsLeft); }, 1000);
}
function displayTimeLeft(seconds) { const minutes = Math.floor(seconds /60); const remainderSeconds = seconds % 60; console.log({minutes, remainderSeconds}); const display = `${minutes}:${remainderSeconds < 10 ? '0' : ''}${remainderSeconds}`; document.title = display; timerDisplay.textContent = display; }
function displayEndTime(timestamp) { const end = new Date(timestamp); const hour = end.getHours(); const adjustedHour = hour > 12 ? hour - 12 : hour; const minutes = end.getMinutes(); endTime.textContent = `Be Back At ${hour}:${minutes < 10 ? '0' : ''}${minutes}`; }
|
Step3. 預設的固定時間倒數按鈕
1 2 3 4 5 6 7 8 9 10
| function startTimer() { const seconds = parseInt(this.dataset.time); timer(seconds); }
buttons.forEach(button => button.addEventListener('click', startTimer));
|
Step4. 自訂時間倒數
1 2 3 4 5 6 7 8 9 10 11
| document.customForm.addEventListener('submit', function(e) { e.preventDefault(); const mins = this.minutes.value; timer(mins * 60); this.reset(); })
|
其他
這篇練習也算是相對簡單的時間,主要是學著用變數把setInterval內容包住,
並且運用clearInterval
來避免多個計時器啟動。
[DEMO]