简体   繁体   中英

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);

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> 

Given a button with id button as so:

<button id="button">Click me</button>

the most basic way to add an event listener for that button to start the timer is by retrieving the element from dom (using querySelector or getElementById ), then add a named event listener function to the element in the dom, such as onclick :

document.querySelector('#button').onclick = function(){
  //your code to start timeer here
};

but you can also do it using addEventListener :

document.querySelector('#button').addEventListener('click',function(){
  //your code to start timeer here
});

or with event delegation, you can add a global click handler to the document, check if the target element was the button, and if so you can then start the timer:

document.addEventListener('click',function(event){
  if(event.target.id==='button'){
    //your code to start timer here
  }
});

there are 900 ways to skin a cat in modern javascript, its up to you to decide which one is most appropriate, and sometimes its a matter of personal preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM