Day 23: Timer
Lesson 2: Timer: 2
We are going to use setInterval
to drive this timer. If you want an accurate timer you shouldn't really use this as setInterval
(and setTimeout
) is not deterministic. That means, if we create an interval to fire every 1,000 ms it might sometimes fire at 1,000 but it will also fire slightly late sometimes. It's more than good enough for what we need and for most timers, however be aware in the future that if you want to run a timer in a browser that actually matters, you should take a different approach that I will cover at the end.
Let's get our variables set up, we need access to the input element, the div to display the current time in, a variable to store the current time in and a variable to store the active running interval.
1const timerElement = document.getElementById("timer"); 2const timeInputElement = document.getElementById("time-input"); 3 4let timerInterval; 5let time = 0;
Let's start our timer with a function called startTimer
(this is already referenced in the onclick
attribute in the HTML)
1function startTimer() { 2 console.log("starting timer"); 3 4 time = timeInputElement.value; 5 6 if (time <= 0) { 7 alert("Time must be more than 0!"); 8 return; 9 } 10 11 timerElement.innerHTML = time; 12 13 timerInterval = setInterval(updateTimer, 1000); 14}
This function:
- Gets the time from the input
- Checks it is greater than 0
- Sets the displayed time to the time the user entered
- Creates an interval that will call a function called
updateTimer
every 1,000 milliseconds
We need to add updateTimer
, add this above startTimer
1function updateTimer() { 2 time--; 3 timerElement.innerHTML = time; 4 5 if (time === 0) { 6 clearInterval(timerInterval); 7 } 8}
This function is called once a second and it decreases the time
left by 1, updates the UI and then if time
is 0 it stops the interval running with clearInterval
.
This is enough to get a basic countdown timer working. Go ahead and click "Start" 🥳