skip to Main Content

I’m continuing with learning javascript and I’ve come across this problem

//let startTime=NaN;

document.getElementById(

    "start_button").addEventListener(
        'click',()=>{
            const startTime = new Date;
            timer();

});

const timer= ()=>{
    setTimeout(()=>{

        const now = new Date;
        const elapsed = now-startTime;
        const seconds = 0;
        document.getElementById("milli_seconds").innerHTML=elapsed;
        console.log("clicked",elapsed);
    
        if(elapsed>=999){
            seconds++;
            elapsed=0;
        }
    
        document.getElementById("seconds").innerHTML=seconds;
    },1);
}

The code should run as a timer stopwatch counting both seconds and miliseconds,
however, the code runs for les than 10ms and then stops

2

Answers


  1. You should use setInterval for your purpose. (And clearInterval to stop.)

    let intervalTimer;
    let startTime; // timestamp
    let elapsed = 0; // milli seconds
    
    document.getElementById("start_button").addEventListener('click', () => {
      startTime = (new Date()).getTime();
      timer();
    });
    
    document.getElementById("stop_button").addEventListener('click', () => {
      clearInterval(intervalTimer);
    });
    
    const timer = () => {
      intervalTimer = setInterval(() => {
    
        elapsed = (new Date()).getTime() - startTime;
        
        let seconds = Math.round(elapsed / 1000);
        let milliSeconds = elapsed;
    
        document.getElementById("seconds").innerHTML = seconds;
        document.getElementById("milli_seconds").innerHTML = milliSeconds;
      }, 1);
    }
    <button id="start_button">start_button</button>
    <button id="stop_button">stop_button</button>
    <div id="seconds"></div>
    <div id="milli_seconds"></div>
    Login or Signup to reply.
  2. As you can see in here, setTimeout takes two arguments, the callback function and the delay in miliseconds.
    You function actually runs once after only one milisecond, and it is actually working properly, exactly like it was coded for.
    If you want to run after a second you should change the second argument (the delay) from 1 to 1000.
    For repeated runs the proper function in setInterval, runing repeatedly every given time.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search