Search code examples
javascripthtmltimercountdown

Javascript countdown timer with 05 instead of 5 seconds?


I have created this one in JavaScript! It is a timer counting down time from 14:59 to 00:00 minutes. What I need to do is prevent seconds from going into one digit.

For example:
14:05 - allowed and needed to achieve
14:5 - not allowed and I need to get rid of this situation.

<html>
<head>
    <script type="text/javascript">
        var interval;
        var minutes = 14;
        var seconds = 05;
        window.onload = function () {
            countdown('atskaite');
        }

        function countdown(element) {
            interval = setInterval(function () {
                var el = document.getElementById(element);
                if (seconds == 0) {
                    if (minutes == 0) {
                        clearInterval(interval);
                        return;
                    } else {
                        minutes--;
                        seconds = 60;
                    }
                }
                el.innerHTML = minutes + ':' + seconds;
                seconds--;
            }, 1000);
        }
    </script>
</head>

<body>
    <div id="atskaite"></div>
</body>
</html>


Any help, please?


Solution

  • Simply add a check before you assign el.innerHTML, like so:

    if (seconds < 10) seconds = '0' + seconds;