Javascript Countdown

javascript

I have searched the web but all the ones readily available are where you specificy a date and it counts down to that date. What I need is something which will simply count down from "27 minutes and 43 seconds" (in that format) all the way down to 0 from whenever they land on the page, anyone got any snippets available?

Best Answer

Something like this should do the trick. I'm bored and decided to do it myself instead of Googling. Just set the minutes and seconds at the top and change the call to countdown inside the onload to the id of the element you want it to update.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script>
    var interval;
    var minutes = 1;
    var seconds = 5;
    window.onload = function() {
        countdown('countdown');
    }

    function countdown(element) {
        interval = setInterval(function() {
            var el = document.getElementById(element);
            if(seconds == 0) {
                if(minutes == 0) {
                    el.innerHTML = "countdown's over!";                    
                    clearInterval(interval);
                    return;
                } else {
                    minutes--;
                    seconds = 60;
                }
            }
            if(minutes > 0) {
                var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
            } else {
                var minute_text = '';
            }
            var second_text = seconds > 1 ? 'seconds' : 'second';
            el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
            seconds--;
        }, 1000);
    }
    </script>
</head>
<body>
<div id='countdown'></div>
</body>
</html>