3

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);
2
  • Humm, you try to get milli second too. And you call your clock function all 1000milli second (1sec).. Isn't working ^^ And second stuff, 1s = 1000ms / 1s != 60ms Commented May 26, 2015 at 19:23
  • msec in the if statement should be 1000, not 60. Commented May 26, 2015 at 19:26

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

1 Comment

oh yes! but its still not incrementing at all, thos not entering the if cycles below

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.