-2

How can I use moment.js to show a timer starting at 00:00:00 and updates every second and put the value in a div?

I want to use that as a timeup-counter.

Thank you very much.

OMEXLU
  • 65
  • 1
  • 6

2 Answers2

1

You can achieve the same by using the inbuilt setInterval function. No need to use moment.js for that

Here is the code

function setTimer() {
  let time = 5 //define your seconds here

  let timer = setInterval(function() {
    if (time === 0) { //check if time is over 
      document.getElementById("timer").innerHTML = "Time up";
      clearInterval(timer); //clear the interval 
    } else {
      time-- 
      document.getElementById("timer").innerHTML = time; 
    }
  }, 1000);
}

setTimer()
<div id="timer"></div>

Hope this helps

Hadi Mir
  • 4,497
  • 2
  • 29
  • 31
  • Thanks for you answer but i need to time up not down :) 00:00:00 -> 00:00:01 -> 00:00:02 -> ... and so on. – OMEXLU Dec 29 '19 at 07:22
  • Just chane time-- to time++ and change if(time === 0 ) to the max value upto which you want to check make sure you set the time initially to 0 – Hadi Mir Dec 29 '19 at 18:19
1

try this, it will help

var timerVar = setInterval(countTimer, 1000);
    var totalSeconds = 0;
    function countTimer() {
       ++totalSeconds;
       var hour = Math.floor(totalSeconds /3600);
       var minute = Math.floor((totalSeconds - hour*3600)/60);
       var seconds = totalSeconds - (hour*3600 + minute*60);
       if(hour < 10)
         hour = "0"+hour;
       if(minute < 10)
         minute = "0"+minute;
       if(seconds < 10)
         seconds = "0"+seconds;
       document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
    }
<div id="timer"></div>
kushal shah
  • 823
  • 6
  • 9