Bernardo Pinheiro
Bernardo Pinheiro

Reputation: 31

Making a timer in Javascript , starting from 00:00:00

with this following code

function clock(){
    /*var message = document.getElementById("timer");
    message.innerHTML = "The time is " + Date();
    */
    var msec = 00;
    var sec = 00;
    var min = 00;

    msec += 1;
    console.log(min + ":" + sec + ":" + msec);
    if (msec == 60) {
        sec += 1;
        msec = 00;
        console.log(min + ":" + sec + ":" + msec);
        if (sec == 60) {
            sec = 00;
            min += 1;
            console.log(min + ":" + sec + ":" + msec);
            if (sec % 2 == 0) {
                alert("Pair");
            }
        }
    }
    document.getElementById("timer").innerHTML = min + ":" + sec + ":" + msec;
}

What I wanted to do is a simple timer that starts on a window load, and every milisec it increments the up to 60, which by then resets to 0 and adds 1 to the seconds which when seconds reaches 60, goes to 0 and increments minutes by 1. Sorta like a stopwatch.

It seems I'm not incrementing properly but I don't know how to increment it.

I'm calling the function with a setInterval which I don't know if its right:

var  timer = setInterval(clock(), 1000);

Upvotes: 3

Views: 3306

Answers (1)

Satpal
Satpal

Reputation: 133403

You need to pass the function reference to setInterval, currently you are passing the return value of clock() which is undefined thus it has no impact.

Also you need to declare msec, sec and min variables out side clock() function.

var timer = setInterval(clock, 1000);
var msec = 00;
var sec = 00;
var min = 00;

var timer = setInterval(clock, 1000);
var msec = 00;
var sec = 00;
var min = 00;

function clock() {
	msec += 1;
	if (msec == 60) {
		sec += 1;
		msec = 00;
		if (sec == 60) {
			sec = 00;
			min += 1;
			if (sec % 2 == 0) {
				alert("Pair");
			}
		}
	}
	document.getElementById("timer").innerHTML = min + ":" + sec + ":" + msec;
}
<div id="timer"></div>

Upvotes: 5

Related Questions