Search code examples
javascripthtmltimer

How to create a simple JavaScript timer?


So, basically I am trying to create a simple JS timer that will start at 00:30, and go all the way to 00:00, and then disappear.

I already have the HTML code :

<div id="safeTimer">
<h2>Safe Timer</h2>
<p id="safeTimerDisplay">00:30</p>
</div>

The element that will display the timer is obviously the paragraph. Now I know that this would be pretty easy to do if I did it the hard-coded way : I would just make a function that will change the paragraph's innerHTML ("00:30", "00:29", "00:28", etc), and then call it every second using setInterval()

How would I do it the easy (not hard-coded) way?


Solution

  • Declare this function and bind it to onload event of your page

    function timer(){
        var sec = 30;
        var timer = setInterval(function(){
            document.getElementById('safeTimerDisplay').innerHTML='00:'+sec;
            sec--;
            if (sec < 0) {
                clearInterval(timer);
            }
        }, 1000);
    }