0

I'm using this library to run a counter in JavaScript: https://github.com/mckamey/countdownjs

Here is what I have in my view:

<p id="countdown-holder", style="font-size:18px;"></p> 

<script>  
  var clock = document.getElementById("countdown-holder")  
  , targetDate = new Date(2015, 12, 10);  

  clock.innerHTML = countdown(targetDate).toString();  
  setInterval(function(){  
    clock.innerHTML = countdown(targetDate).toString();  
  }, 1000);  
</script> 

Currently, when the countdown finishes, it starts counting upwards.

How do I get the counter to stop when it hits 0 and display an alert(); message?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Katie H
  • 2,283
  • 5
  • 30
  • 51

1 Answers1

2

Inside your interval function check to see if Date.now() is greater than targetDate. If so, clear the timeout and display an alert.

var clock = document.getElementById("countdown-holder")  
var targetDate = new Date(2015, 7, 7);

var intervalId = setInterval(function(){
    if(Date.now() >= targetDate) {
      clearInterval(intervalId);
      alert('Hi.');
      return;
    }
    clock.innerHTML = (targetDate)
  }, 1000);
<div id="countdown-holder">
         
</div>
ray
  • 26,557
  • 5
  • 28
  • 27
  • Inside the setInterval function I put: if (targetDate > Date.now) { alert("done!"); } and it's doing the same thing, counting upwards without invoking the alert – Katie H Aug 09 '15 at 18:41
  • 1
    Your comparison is backwards. You want to see if now is greater than target. (My fault. That's what I said in my answer. Fixed.) What do you have targetDate set to? – ray Aug 09 '15 at 18:52