12

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?

2
  • 1
    Create a variable and deduct it by one each time the interval fires? Commented Jul 22, 2015 at 9:44
  • 3
    I am struggling to understand your interpretation of the word "hard coded". Commented Jul 22, 2015 at 9:45

4 Answers 4

27

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! That's the simplest one and it worked ! I don't know why I didn't think about that solution before.
The only thing that I do not understand is why would I bind it to onload? I didn't mention that I want the timer to start when I press the button (I know how to do that though).
Of course, you can bind this function to any event you need
Thanks, but How do I stop the setInterval() ? Something like this : ? if(sec <= 0){ ??? }
@aCodingN00b mark it as an answered if this satisfied you
8

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.

1 Comment

I like how this answer shows minutes as well as seconds for those who need 60+ seconds.
3

Please try with the below code snippet.

<!DOCTYPE html>
<html>
<body>

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

<script>
var myVar = setInterval(function(){ myTimer() }, 1000);
var secondlimit = 30;

function myTimer() {
if(secondlimit == 0)
{
    myStopFunction();
}

document.getElementById("safeTimerDisplay").innerHTML = '00:' + zeroPad(secondlimit,2);
secondlimit = secondlimit  - 1;

}

function myStopFunction() {
    clearInterval(myVar);
}

function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}

</script>

</body>
</html>

Comments

0

Timer Class

class Timer {

    constructor() {
        this.time = 0;
        this.element = null;
        this.control = true;
        this.callback = null;
        this.timeLimit = 10;
    }

    set(time, id, callback = null) {
        this.time = time;
        this.element = document.getElementById(id);
        this.callback = callback;
    }

    setTimeLimit(time) {
        this.timeLimit = time;
    }

    start(type = 'COUNT_DOWN') {
        this.control = true;

        setTimeout(() => {
            if(type == 'COUNT_DOWN')
                this.countDown();
            else if(type == 'COUNT_UP') 
                this.countUp();
        }, 1000);
    }

    format() {
        let hours = parseInt(this.time / 3600);
        let timeLeft = this.time - hours * 3600;
        let minutes = parseInt(timeLeft / 60);
        timeLeft = timeLeft - minutes * 60;
        let seconds = timeLeft;
        
        hours = hours.toString();
        minutes = minutes.toString();
        seconds = seconds.toString();
    
        if (hours.length == 1)
            hours = '0' + hours;
        if (minutes.length == 1)
            minutes = '0' + minutes;
        if (seconds.length == 1)
            seconds = '0' + seconds;
        
        return hours + ':' + minutes + ':' + seconds;
    }

    countDown() {
        if(!this.control)
            return;
        let timerblock = this.element;
        timerblock.innerHTML = this.format();
        timerblock.style.display = 'block';

        if (this.time <= 59) {
            timerblock.style.color = 'red';
        }
    
        if (this.time <= 0) {
            timerblock.innerHTML = 'Time end!';
            this.callback();
            this.stop();
        }
        else {
            setTimeout(() => {
                this.countDown();
            }, 1000);
            this.time--;
        }
    }

    countUp() {
        if(!this.control)
            return;
        let timerblock = this.element;
        timerblock.innerHTML = this.format();
        timerblock.style.display = 'block';
    
        if(this.time >= this.timeLimit) {
            timerblock.innerHTML = 'Timer Limit Exceed!';
            this.callback();
            this.stop();
        }
        else {
            setTimeout(() => {
                this.countUp();
            }, 1000);
            this.time++;
        }
    }

    stop() {
        this.control = false;
    }
}

Create a div set attribute id='timer'

<div id="timer"></div>

Create a callback function which you want to call after

  1. time == 0 in COUNT_DOWN Timer
  2. time limit exceeds in COUNT_UP Timer
const callback = () => {
    console.log('callback function called from timer');
}

Create timer instance

const timer = new Timer();

set method take 3 arguments

  1. time
  2. dom element id
  3. callback function
timer.set(10, 'timer', callback);

Finally call start function to start the timer

It takes a string 'COUNT_DOWN' or 'COUNT_UP' by default it is 'COUNT_DOWN'

timer.start('COUNT_DOWN');

To stop timer

timer.stop();

View Demo Code on Github

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.