Bootcamp
Search…
1.8: Timer

Introduction

Use setInterval to create a countdown timer.

Global Variables and Initialisation

1
let milliseconds = 5000;
2
const delayInMilliseconds = 1;
3
const output = document.createElement('div');
4
output.innerText = milliseconds;
5
document.body.appendChild(output);
Copied!

Timer Code

1
const ref = setInterval(() => {
2
output.innerText = milliseconds;
3
​
4
if (milliseconds <= 0) {
5
clearInterval(ref);
6
}
7
​
8
milliseconds -= 1;
9
}, delayInMilliseconds);
Copied!

Exercise

Create a timer that counts up instead of down. Have it stop after the same amount of time as the countdown timer above. (5000 milliseconds).