bool3max
bool3max

Reputation: 2865

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?

Upvotes: 11

Views: 70364

Answers (4)

Ishwar Baisla
Ishwar Baisla

Reputation: 1

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

Upvotes: 0

Mikhail
Mikhail

Reputation: 671

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);
}

Upvotes: 27

Jayesh Goyani
Jayesh Goyani

Reputation: 11154

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>

Upvotes: 3

Sotiris Kiritsis
Sotiris Kiritsis

Reputation: 3346

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.

Upvotes: 8

Related Questions