Search code examples
javascripthtmlsettimeout

JavaScript timeout() not working properly


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


Solution

  • 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.