In this lesson I create a countdown timer application.
First I initialise a 'countdown' variable. Then I get the following elements: 'timerDisplay', 'endTime', [data-time]. Then I listen for the following events:
-
[data-time]
-
document.customForm
- 'submit', function(e) {}
- First prevent the event default to ensure the page doesn't refresh (e.prefentDefault();). Then set 'mins' to 'this.minutes.value' and run timer(mins * 60) to send the minutes as seconds into the timer() function.
In startTimer() - Set 'seconds' to the [data-time] value (parseInt(this.dataset.time)). Then run timer(seconds).
In timer(seconds) - First clearInterval(countdown). Next set 'now' and 'then', both are in milliseconds.
Then run displayTimeLeft(seconds) and displayEndTime(then). Finally set the 'countdown'.
- In displayTimeLeft(seconds) - Get the 'minutes' (seconds / 60), 'remainderSeconds' (seconds % 60), then 'display' the 'minutes' and 'remainderSeconds' in a string. Prepend a '0' if 'remainderSeconds < 10. Finally, output 'display' to the 'document.title' and to 'timerDisplay'.
- In displayEndTime(timestamp) - Create a new date object 'end' from the passed in 'timestamp'. From that get 'hours' (end.getHours()). Then calculate 'adjustedHour' to adjust to a 12hr clock. Next get 'minutes' (end.getMinutes()). Finally, output the end time to 'endTime.textContent'.
- In 'countdown' - Every second, set 'secondsLeft' (Math.round((then - Date.now()) / 1000). Check if there are any 'secondsLeft', If so, clearInterval(countdown). Either way, displayTimeLeft(secondsLeft).
See the Pen
JavaScript30 - 29 - Countdown Timer by Corey Noble (@CoreyNoble)
on CodePen.