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.
<p class="countdownDisplay"></p>
<button>Start</button>
let countdown = ["5", "4", "3", "2", "1", "Time's up!"];
let btn = document.querySelector("button");
let countdownDisplay = document.querySelector(".countdownDisplay");
btn.addEventListener("click", countdownFunction);
function countdownFunction() {
for (let i = 0; i < countdown.length; i++) {
countdownDisplay.innerText = countdown[i];
console.log(countdown[i]);
}
}
setInterval(countdownFunction, 5000);
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:
let countdown = ["5", "4", "3", "2", "1", "Time's up!"];
let btn = document.querySelector("button");
let countdownDisplay = document.querySelector(".countdownDisplay");
//declaring interval outside the function because we need to stop it at the end of counting
let interval
const startInterval = () => {
interval = setInterval(countdownFunction, 1000);
}
btn.addEventListener("click", startInterval);
//declaring the innitial value (first position of the array)
let i = 0
function countdownFunction() {
countdownDisplay.innerText = countdown[i++];
//if i is the last element of the array, stop the counting
if(i==countdown.length)
clearTimeout(interval)
}
Remove "for" loop from countdownFunction()
.
let countdown = ["5", "4", "3", "2", "1", "Time's up!"];
let i= 0;
function countdownFunction() {
console.log(countdown[i])
++i;
}
setInterval(countdownFunction, 5000);
A little late but here is a solution with setTimeout. the advantage with this version, it ends after the countdown and does not continue like with setInterval.
const countdown = ["5", "4", "3", "2", "1", "Time's up!"];
const countdownDisplay = document.querySelector(".countdownDisplay");
const button = document.querySelector("button");
function countdownFunction(i) {
let _i = i++;
setTimeout(() => {
console.log(countdown[_i])
countdownDisplay.innerText = countdown[_i];
}, 1000 * _i, countdown[_i]);
}
button.addEventListener("click", () => {
for(let i = 0; i<countdown.length; i++) {
countdownFunction(i)
}
});
<p class="countdownDisplay">Click</p>
<button>Start</button>