Reputation: 106
I'm attempting to create a countdown timer from a set time, say, 2 hours.
I have a button and a label and I'd like, when the button is pressed, for the timer to begin, being displayed after the "Time Remaining:" - if the button is pressed again, the timer resets.
Here's the code I currently have:
var itemClick = document.getElementById('item1');
itemClick.addEventListener('click', function(){
itemHandler();
})
function itemHandler(){
var label = document.getElementById('item1-label');
if (label.innerHTML == "") {
label.innerHTML = "Time Remaining:";
}
}
How exactly would I implement this?
Upvotes: 0
Views: 244
Reputation: 163
var timer = setInterval(timerCount, 1000);
var t = 10;
function timerCount() {
t--;
if (t < 0) {
console.log("times up");
clearInterval(timer);
} else {
console.log(t);
}
}
It's easiest way to make a countdown as far as I know (and I don't know much;-) ) You seem familiar with basic DOM manipulation, so I will leave the rest to you. Remember, to clear the interval, you have to first set it using a variable.
Upvotes: 2
Reputation: 958
This should do the job:
function itemHandler(){
var label = document.getElementById('item1-label');
if (label.innerHTML == "") {
var countdown = 10;
label.innerHTML = `Time Remaining: ${countdown}`;
var countdownInterval = setInterval(function() {
if (countdown > 0) {
label.innerHTML = `Time Remaining: ${countdown}`;
countdown -= 1;
}
}, 1000);
} else {
clearInterval(countdownInterval);
label.innerHTML = '';
}
}
Upvotes: 2