click button need start timer

Advertisements

hi i want to when i click button, my timer start working. But its just show 1 time.

setInterval(myFunc, 1000);

function myFunc() {
    button = document.getElementById("btn");
    let date = new Date();
    
    button.addEventListener("click", () => {
        document.getElementById("h1text").innerHTML = 
        date.getHours() + ":" +
        date.getMinutes() + ":" + 
        date.getSeconds();
    });
}

i want to work this timer all time, not for one time. like this code but i need to start with button click

setInterval(myFunction, 1000);

function myFunction() {
  let d = new Date();
  document.getElementById("demo").innerHTML=
  d.getHours() + ":" +
  d.getMinutes() + ":" +
  d.getSeconds();
}

>Solution :

Attach just one click listener, outside the interval. Inside the interval, set the content of the element only if date has been assigned to.

document.getElementById("btn").addEventListener(
  'click',
  () => {
    const fn = () => {
      const date = new Date();
      document.getElementById("h1text").innerHTML = 
        date.getHours() + ":" +
        date.getMinutes() + ":" + 
        date.getSeconds();
    };
    fn();
     setInterval(fn, 1000);
  },
  { once: true }
);
<h1 id="h1text"></h1>
<button id="btn">click</button>

You might also want to pad the numbers.

document.getElementById("btn").addEventListener(
  'click',
  () => {
    const fn = () => {
      const date = new Date();
      document.getElementById("h1text").innerHTML = 
        String(date.getHours()).padStart(2, 0) + ":" +
        String(date.getMinutes()).padStart(2, 0) + ":" + 
        String(date.getSeconds()).padStart(2, 0);
    };
    fn();
     setInterval(fn, 1000);
  },
  { once: true }
);
<h1 id="h1text"></h1>
<button id="btn">click</button>

Leave a ReplyCancel reply