I have a timer which counts down 2 hours. I want the timer to run only when a button, item1, is pressed. However, right now, the timer is running immediately when the page opens. I think it's something to do with the interval, but, I'm not sure what to change.
How can I change this so that it only runs when the button is clicked? (And the timer stops when the button is clicked a second time).
Here's the code:
var itemClick = document.getElementById('item1');
itemClick.addEventListener('click', function(){
itemHandler();
})
var count = 7200;
var counter = setInterval(itemHandler, 1000); //1000 will run it every 1 second
function itemHandler() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("item1-label").innerHTML = hours + " hour(s) " + minutes + " minutes and " + seconds + " seconds remaining.";
}