I am trying to get my buttons to start counting down when I select a specific time. As of now when I click on one it only shows the time, it doesn't start the countdown.
<html>
<div class="app">
<div class="time-select">
<button data-time="120">2 Minutes</button>
<button data-time="300">5 Minutes</button>
<button data-time="600">10 Minutes</button>
</div>
<div class="timer-container">
<h3 class="time-display">0:00</h3>
</div>
</div>
</html>
const timeDisplay = document.querySelector(".time-display");
const timeSelect = document.querySelectorAll(".time-select button");
let fakeDuration = 600;
timeSelect.forEach(option => {
option.addEventListener("click", function(){
fakeDuration = this.getAttribute("data-time");
timeDisplay.textContent = `${Math.floor(fakeDuration / 60)}:${Math.floor(fakeDuration %
60)}`;
});
});
ontimeUpdate = () => {
let elapsed = fakeDuration;
let seconds = Math.floor(elapsed % 60);
let minutes = Math.floor(elapsed / 60);
timeDisplay.textContent = `${minutes}:${seconds}`;
};
You need to use setInterval() - additionally I fixed the way you calculate minutes and seconds. JS uses milliseconds - it's generally best to standardize time-keeping/counting to fit into JS's existing rules.
const timeDisplay = document.querySelector(".time-display");
const timeSelect = document.querySelectorAll(".time-select button");
let fakeDuration, interval
timeSelect.forEach(option => {
option.addEventListener("click", function() {
clearInterval(interval)
fakeDuration = +this.getAttribute("data-time");
interval = setInterval( () => ontimeUpdate(), 1000)
});
});
ontimeUpdate = () => {
fakeDuration -= 1000;
if (fakeDuration <= 0) clearInterval(interval)
let minutes = ('0' + Math.floor(fakeDuration / 60000)).slice(-2);
let seconds = ('0' + (fakeDuration % 60000)/1000).slice(-2);
timeDisplay.textContent = `${minutes}:${seconds}`;
};
<div class="app">
<div class="time-select">
<button data-time="120000">2 Minutes</button>
<button data-time="300000">5 Minutes</button>
<button data-time="600000">10 Minutes</button>
</div>
<div class="timer-container">
<h3 class="time-display">0:00</h3>
</div>
</div>