0

I want to make a countdown that starts on 5 minutes and goes to 0 with the pass of the time.

Here is my code:

var x = setInterval(function() {
  var t = 300;
  var minutes = Math.floor(t / 60);
  var seconds = Math.floor(t / 5; 
  document.getElementById("demo").innerHTML = minutes + ":" + seconds;
  if (t < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
},1000);
<p id="demo"></p>

It doesn't work. I know how to do it with a specific date, but it doesn't work with an established amount of time.

Can someone help me?

FZs
  • 16,581
  • 13
  • 41
  • 50
  • 1
    Does this answer your question? [The simplest possible JavaScript countdown timer?](https://stackoverflow.com/questions/20618355/the-simplest-possible-javascript-countdown-timer) – Flori Bruci May 24 '20 at 11:53
  • You forgot to close the parenthesis in the declaration of `seconds`, and you should move the declaration of `t` before the `setInterval` line and decrement it inside... – FZs May 24 '20 at 12:00
  • It solves a lot, thanks. But I want to change the text when the countdown finish. With that code, at the end of the countdown the text continue without changes and the timer starts again. –  May 24 '20 at 12:04
  • Isn't your code gonna run infinitely? After every 1 sec you are setting `t` to 300 and checking if this is less than 0. – ABGR May 24 '20 at 12:08
  • Oh FZs that's right! Now it works. Thanks –  May 24 '20 at 12:09

1 Answers1

0

New code, that works (thanks to FZs and Flori Bruci):

 <p id="demo"></p>
 <script> 
  var t = 27; 
     var x = setInterval(function() {
     var minutes = Math.floor(t / 60); 
     var seconds = Math.floor(t / 5); 
     document.getElementById("demo").innerHTML = minutes + ":" + seconds; 
     t--;
         if (t < 0) { 
             clearInterval(x); 
             document.getElementById("demo").innerHTML = "EXPIRED"; 
         } 
     }, 200); 
 </script>