Can someone please tell me how can i write code for counting seconds in js without using Date() inbuilt object

I tried but the thing is it is going infinite loop,
as it will never go to stop function definition when it is running in while loop,
I don’t know where to put the stop function
any suggestion please, Any suggestions??

function Stopwatch(){
    let startcount=0;
    let stopcount=0;
    let flag=true;
    let i=0;
    this.start= function(){
        if(startcount===1){
            throw new Error("stop watch already started");
        }
            startcount=1;
    while(flag){
        i++
    }

    }
    stop= function(){
        if(stopcount===1){
            throw new Error("stop watch already stopped");
        }
        stopcount=1; 
    }
    let duration=i/1000;
    Object.defineProperty(this,'duration',{
        get:function(){
            stopcount=0;
            startcount=0;
            return duration;
        }
    })
    this.reset=function(){
        startcount=0;
        stopcount=0;
    }
}
k=new Stopwatch();
k.start()
k.stop()
console.log(k.duration)

What are you trying to do, exactly?

Short answer: You need multi-threading to implement a stopwatch like functionality.

Longer answer: As you pointed out, once you call the start function, it goes into an infinite loop, because there’s nothing there to stop the while (flag) loop. You need some kind of interrupt to stop that whole loop process. Multithreading is one way to achieve it You have one thread to handle the counting and another thread to handle the logic for stopping. For example, you start one thread to start counting. Then you start another thread to monitor the mouse click on the stop button. When the second thread detects the mouse click, it sets the variable flag to false. The first thread is faithfully counting up in the while (flag) loop. But this execution is interrupted momentarily by the second thread executing flag = false; When the first thread restart counting after the interrupt, the flag is false, so the looping stops. I’m missing a lot of details, but this is the gist of multithreading. You can look up Javascript multithreading for details.

Depending on what you need to achieve, you may not need multithreading. setTimeout / clearTimeout may do the trick.

Yeah, multithreading is getting a little advanced. As mentioned, there are things like setTimeout and setInterval, which hook into the browsers timer thread (assuming we’re in a browser for this. There may be libraries to make it easier.

I could see using setTimeout or setInterval to handle the display (if you want a stopwatch on the screen) and then using the Date timestamps to get the final. But there is a certain level of imprecision in these - things like setInterval will sometimes take ever so slightly longer than expected. I think I did one once where I fired it off every 1/10th of a second. The number displayed was still driven by Date, but it updated every 1/10th of a second - that way even if it was updated a little late, the problem would not compound.

There may also be libraries that help with a lot of these.

My short answer was not accurate. If it is purely a stopwatch functionality, setTimeout or setInterval should do the work. You said “counting seconds.” If you want some action to be taken (just once) at some later time, then you use setTimeout and specify the function to call and the time delay. If you want to display a value every second, for example, then you use setInterval and specify the function to call and the time interval of 1 second (1000 milliseconds). This is probably the most likely scenario you’re looking for, like you have a quiz question on the page and want to display a countdown timer. Here’s a straight JS that starts a countdown timer when the start button is pressed and stops the timer when the timer value becomes 0 or the stop button is pressed. I put everything in a single html with no css to keep it focused on JS part. Notice that I’m disabling the start button when the timer starts. If I don’t do this, then the user can keep on clicking the start button and initiates multiple timers.

<!DOCTYPE html>
<html>
  <head>
    <script>
      const start = 30;
      const tick = 1000; // 1000 millisec == 1 sec
      let count = start;
      let timer_func = null;
    
      function startTimer() {
        count = start;
        document.getElementById("clock").innerHTML = count;
        document.getElementById("start_btn").disabled = true;
        timer_func = setInterval(countdown, tick);  //calls countdown every 'tick' millisecs
      }
    
      function countdown() {
        count--;
        document.getElementById("clock").innerHTML = count;
        if (count==0) {
          stopTimer();
        }
      }
    
      function stopTimer() {
        clearInterval(timer_func);  //disables timer_func, i.e., stops the count down
        timer_func = null;
        document.getElementById("start_btn").disabled = false;
      }
    
    </script>

  </head>
<body>

<h1>A simple countdown timer</h1>

<h1  id="clock">timer</h1>

<button onclick="startTimer()" id="start_btn">Start</button>
<button onclick="stopTimer()">Stop</button>

</body>
</html>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.