Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

click button need start timer

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading