DevelopPHP.com
Web Development Training System

Countdown Timer Tutorial setTimeout clearTimeout

Learn to program JavaScript countdown scripts that will update your HTML page when the timer reaches zero. We use a custom function that utilizes setTimeout and clearTimeout to start the countdown, as well as making it shut off when the countdown reaches 0 and updating the page. <script> function countDown(secs,elem) { var element = document.getElementById(elem); element.innerHTML = "Please wait for "+secs+" seconds"; if(secs < 1) { clearTimeout(timer); element.innerHTML = '<h2>Countdown Complete!</h2>'; element.innerHTML += '<a href="#">Click here now</a>'; } secs--; var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000); } </script> <div id="status"></div> <script>countDown(10,"status");</script>
CountdownTimersetTimeoutclearTimeout