Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start a timer on a click?

I'm trying to have a timer start when the user makes the first click on a page. Been doing a lot of research and for the life of me, can't figure it out. I think I should use a document.addEventListener but am not sure where it goes.

let min = 0;
let sec = 0;


function myTimer() {
  if (counting) {
    timer.innerHTML = min + " minutes " + sec + " seconds";
    sec++;
    if (sec >= 60) {
      sec = 0;
      min++;
    }
  }
}


//Start the timer

let startTimer = setInterval(function() {
  myTimer();
}, 1000);
like image 505
Duble-D Avatar asked Mar 15 '26 11:03

Duble-D


1 Answers

Just add a click listener to document that calls the setInterval:

let min = 0;
let sec = 0;


function myTimer() {
  timer.innerHTML = min + " minutes " + sec + " seconds";
  sec++;
  if (sec >= 60) {
    sec = 0;
    min++;
  }
}


//Start the timer
document.addEventListener('click', () => {
  setInterval(myTimer, 1000);
}, { once: true });
<div id="timer">click somewhere</div>
like image 124
Snow Avatar answered Mar 18 '26 01:03

Snow