0

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.";
}
xstax
  • 96
  • 2
  • 11

2 Answers2

1
var counter = null;

itemClick.addEventListener('click', function(){
    if (counter) {
        clearInterval(counter);
        counter = null;
    } else {
        counter = setInterval(itemHandler, 1000);
    }
})

Start and stop the interval based on clicking the button, only.

Taplar
  • 24,788
  • 4
  • 22
  • 35
  • Got a "counter is not defined" error. When I created a variable for it, nothing happened. – xstax Aug 25 '20 at 15:37
1

Your function isn't calling itself. It's being called only by the event handler and the setInterval timer.

It sounds like you didn't intend to start the interval timer immediately. If that's the case, move the code starting the interval timer into the event handler:

var itemClick = document.getElementById('item1');
var counter = 0;
itemClick.addEventListener('click', function(){
    itemHandler(); // Include this if you want it to run right away, since the
                   //  first timer callback will take a second
    counter = setInterval(itemHandler, 1000); //1000 will  run it every 1 second
});

You might also want to disable the button or something while the timer is running, or perhaps allow cancelling with another button click.

Disabling the button:

var itemClick = document.getElementById('item1');
var counter = 0;
itemClick.addEventListener('click', function(){
    itemClick.disabled = true;
    counter = setInterval(itemHandler, 1000); //1000 will  run it every 1 second
});

and in itemHandler:

if (count == -1) {
    clearInterval(counter);
    itemClick.diabled = false; // *** Added
    return;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    This worked, but, yeah, I'll need to disable the button; if I keep pressing the button, it increases the timer speed by 1s. Thank you. – xstax Aug 25 '20 at 15:38