Search code examples
javascriptjquerysetintervalcountdownjs.js

Stopping countdown timer Javascript and invoking action


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?


Solution

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