0

I have this timer that counts down from 10 minutes to 0. What I need it to do now is alert('you've finished') when it gets to 0? I tried adding if (mins == 0 alert('hi')); to the Decrement() function but nothing gets picked up.

<!DOCTYPE html>
<html>
<head> 

<link href='http://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/ico" href="favicon.ico">

<title>SAGGY</title>

</head>

<body>

<script>        
    var mins = 10;  //Set the number of minutes you need
    var secs = mins * 60;
    var currentSeconds = 0;
    var currentMinutes = 0;
    setTimeout('Decrement()',1000);

    function Decrement() {
        currentMinutes = Math.floor(secs / 60);
        currentSeconds = secs % 60;
        if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
        secs--;
        document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
        if(secs !== -1) setTimeout('Decrement()',1000);
    } 

</script>

<h1 id="title"> 
  START THE TIMER
</h1>

<button onclick="Decrement()">GO!</button> 

<h2 id="timerText">######</h2>

<br/>

<textarea rows="15" cols="60" id="text">

</textarea> 

<h2 id="finish" class="finish">Copyright BibBoy &#174  2014 #ImYourMum</h2>

</body>
</html>

1 Answers1

1

You can reuse condition you already have:

if (secs !== -1) {
   setTimeout('Decrement()',1000);
   // or better:
   // setTimeout(Decrement, 1000);
} else {
   alert('you\'re done');
}

Also note that you don't need to use string passed to setTimeout() - setTimeout(Decrement, 1000); would work just fine.

Here is the JSFiddle demo adjusted so the timer counts down from 5 seconds, not 10 minutes.

Another note that I have is that, by convention, people usually use lowercase function names. Function names with captial first letter are usually used to denote constructors.

kamituel
  • 34,606
  • 6
  • 81
  • 98