-2

I just practice using Interval and clearInterval methods. I want to restart setInterval after calling clearInterval. Here is the code

var ppp = document.getElementById('pp');
var timer = setInterval(Func, 1000);
var seconds = 0;

function Func() {
  ppp.innerText = seconds++;
  if (seconds > 10) {
    clearInterval(timer);
  }
  if (seconds == 10) {
    restart();
  }
}

function restart() {
  seconds = 0;
  timer = setInterval(Func, 1000);
}
<p id="pp"></p>

Output

not counting by one by one Expected 0 1 2 3 4 5 6 7 8 9 10 and restart from 0~10

IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • 2
    You have to clear the previous timer if you want to restart. There's no point checking to see if `seconds` is greater than 10 if you're going to restart as soon as it is equal to 10. – Pointy Oct 18 '22 at 02:45

1 Answers1

1

You are checking something for greater than 10 after you already set it to zero when it is 10.

var ppp = document.getElementById('pp');
var timer = setInterval(Func, 250);
var seconds = 0;

function Func() {
  ppp.innerText = seconds++;
  if (seconds == 10) {
    clearInterval(timer);
    restart();
  }
}

function restart() {
  seconds = 0;
  timer = setInterval(Func, 250);
}
<p id="pp"></p>
IT goldman
  • 14,885
  • 2
  • 14
  • 28