Search code examples
javascripthtmlcountdown

Countdown on JavaScript


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?


Solution

  • 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>