Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 471
bool3max Avatar asked Nov 28 '22 01:11

bool3max


2 Answers

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);
}
like image 127
Mikhail Avatar answered Dec 05 '22 07:12

Mikhail


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.

like image 38
Sotiris Kiritsis Avatar answered Dec 05 '22 08:12

Sotiris Kiritsis