Simple clock that counts down from 30 seconds and executes a function afterward

Use setInterval to set up a timer. Within this timer, you can update some text in your page and when the time is up, you can call whatever function you want:

var timeLeft = 30;
    var elem = document.getElementById('some_div');
    
    var timerId = setInterval(countdown, 1000);
    
    function countdown() {
      if (timeLeft == -1) {
        clearTimeout(timerId);
        doSomething();
      } else {
        elem.innerHTML = timeLeft + ' seconds remaining';
        timeLeft--;
      }
    }
<div id="some_div">
</div>


Check out setTimeout and setInterval:

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

Tags:

Javascript