0

I was making a Timer with Javascript, until I came across a problem. While counting the seconds, I saw that the seconds would not reset to 0 every minute. Here is my code:

let sec = 0;
let double = -0;
let meme = setInterval(function() {
  document.open();
  document.write(double + "Min" + " " + sec + "Sec");
  sec++;

}, 1000);
setInterval(function() {
  document.write(double);

  double++;
}, 61000);
setInterval(function() {
  document.open();
}, 60999);

Is there any way to reset the seconds after 60 intervals?

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Possible duplicate of [How do I reset the setInterval timer?](https://stackoverflow.com/questions/8126466) – Dr. Vortex Nov 04 '22 at 17:08
  • Man is 2022 and you use document.write ? Did you learn js 20 years ago ? – Robert Nov 04 '22 at 17:18
  • use `... + (sec % 60) + ...`. But you will also note that the timers get out of sync because they do not run at *exactly* the time specified, only at *about* that time. You should only have one timer that uses a fixed point (e.g. `let datum = Date.now()` then calculate the minutes and seconds that have elapsed since the datum as `let elapsed = Date.now() - datum`. Then convert elapsed (which will be milliseconds) to minutes and seconds. – RobG Nov 05 '22 at 07:43

1 Answers1

0

Add if (sec >= 60) sec = 0; after sec++, like this:

let sec = 0;
let double = -0;
let meme = setInterval(() => {
  document.open();
  document.write(double + "Min" + " " + sec + "Sec");
  sec++;
  if (sec >= 60) sec = 0;
}, 1000);

setInterval(() => {
  document.write(double);
  double++;
}, 61000);

setInterval(() => {
  document.open();
}, 60999);
Volodymyr Sichka
  • 531
  • 4
  • 10