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?
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);
}
                        Try the following code:
function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (--timer < 0) {
            timer = 0;
            // timer = duration; // uncomment this line to reset timer automatically after reaching 0
        }
    }, 1000);
}
window.onload = function () {
    var time = 60 / 2, // your time in seconds here
        display = document.querySelector('#safeTimerDisplay');
    startTimer(time, display);
};
You can see a Jsfiddle example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With