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);
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:
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) }