0

I found this javascript and it starts a new count down after finished in a loop

<script>
  var countdownNumberEl = document.getElementById('countdown-number');
  var countdown = 10;

  countdownNumberEl.textContent = countdown;

  setInterval(function() {
    countdown = --countdown <= 0 ? 10 : countdown;
    countdownNumberEl.textContent = countdown;
  }, 1000);
</script>
Naveen Kumar V
  • 2,559
  • 2
  • 29
  • 43
MinD
  • 11
  • 2
    What do you think `--countdown <= 0 ? 10 : countdown` does? – Jonas Wilms Jul 15 '19 at 13:35
  • It's not a loop, it's interval timer. When your `countdown` value equals 0, it resets to 10 again and so on. You just need to assign `setInterval` to a variable and then `clearInterval` when value is `0`. – Evgeny Melnikov Jul 15 '19 at 13:38
  • I edited your code with clearInterval() method on the other thread. Please see if it helps you. https://stackoverflow.com/a/57041611/3506426 – Ishara Amarasekera Jul 15 '19 at 14:15

1 Answers1

2

SetInterval returns a unique ID.

var intervalId = setInterval( function(){}, 1000);

so, when you want it to stop, you will just call clearInterval(intervalId)

If you want to call it in the function itself, you need to just have the correct conditional to monitor when you want it to stop it you would need to reference the global or scoped identifier.

In your example, you are using a countdown variable.

So you can say something like:

if (countdown <= 0) clearInterval(intervalId);

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129