I’m a beginner. I’d like to create a simple countdown from an array started by a button event listener. I want to display the elements of the array after a delay in p class=”countdownDisplay”. However, it doesn’t work the way I want. There’s no delay.
JavaScript
x
3
1
<p class="countdownDisplay"></p>
2
<button>Start</button>
3
JavaScript
1
17
17
1
let countdown = ["5", "4", "3", "2", "1", "Time's up!"];
2
3
let btn = document.querySelector("button");
4
5
let countdownDisplay = document.querySelector(".countdownDisplay");
6
7
btn.addEventListener("click", countdownFunction);
8
9
function countdownFunction() {
10
for (let i = 0; i < countdown.length; i++) {
11
countdownDisplay.innerText = countdown[i];
12
console.log(countdown[i]);
13
}
14
}
15
16
setInterval(countdownFunction, 5000);
17
Advertisement
Answer
If you call the for loop, it will add from 0 until 5 at once and your code will not work. I hope the commented code below helps you:
JavaScript
1
25
25
1
let countdown = ["5", "4", "3", "2", "1", "Time's up!"];
2
3
let btn = document.querySelector("button");
4
5
let countdownDisplay = document.querySelector(".countdownDisplay");
6
7
//declaring interval outside the function because we need to stop it at the end of counting
8
let interval
9
10
const startInterval = () => {
11
interval = setInterval(countdownFunction, 1000);
12
}
13
14
btn.addEventListener("click", startInterval);
15
16
//declaring the innitial value (first position of the array)
17
let i = 0
18
19
function countdownFunction() {
20
countdownDisplay.innerText = countdown[i++];
21
//if i is the last element of the array, stop the counting
22
if(i==countdown.length)
23
clearTimeout(interval)
24
}
25