My setInterval function is not working as intended

Asked

Viewed 34 times

0

Here’s the code:

//Função para contar os segudos
function conta_seg(){
	sec++;
	if (sec < 10 && min == 0) {
		document.getElementById("conta-tempo").innerHTML = "00:0" + sec;
	}else if (sec < 60 && min == 0) {
		document.getElementById("conta-tempo").innerHTML = "00" + sec;
	}else{
		sec %= 60;
		min++;
		if (min < 10 && sec < 10) {
			document.getElementById("conta-tempo").innerHTML = "0" + min + ":0" + sec;
		}else if (min < 10 && sec <60) {
			document.getElementById("conta-tempo").innerHTML = "0" + min + ":" + sec;
		}else if (min < 60 && sec < 10) {
			document.getElementById("conta-tempo").innerHTML = min + ":0" + sec;
		}else if (min < 60 && sec < 60) {
			document.getElementById("conta-tempo").innerHTML = min + ":" + sec;
		}
	}
}

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

I checked which error with console.log and found that something was Undefined. What can I do to solve the problem and the program count the seconds normally?

  • 1

    Inês, you are using the variables sec and min, but in your code apparently they have not been declared anywhere. Try to declare them, that this should solve your problem.

  • Edit the question and enter the returned error code.

1 answer

2


In addition to not having declared the variables sec and min, function call on the setInterval is wrong:

setInterval(conta_seg(), 1000);
                     ↑↑

When you set the parentheses, you are running the function directly (and only once) and not making it a function to be executed every turn of the setInterval.

The correct is to reference the external function (without parentheses):

setInterval(conta_seg, 1000);

I reproduced the code with these corrections and it is working (see below), but I believe there are other problems of logic/ programming, because after the clock reaches 1 minute, the result starts to get strange. Behold:

//Função para contar os segudos
var sec = 0, min = 0;

function conta_seg(){
	sec++;
	if (sec < 10 && min == 0) {
		document.getElementById("conta-tempo").innerHTML = "00:0" + sec;
	}else if (sec < 60 && min == 0) {
		document.getElementById("conta-tempo").innerHTML = "00" + sec;
	}else{
		sec %= 60;
		min++;
		if (min < 10 && sec < 10) {
			document.getElementById("conta-tempo").innerHTML = "0" + min + ":0" + sec;
		}else if (min < 10 && sec <60) {
			document.getElementById("conta-tempo").innerHTML = "0" + min + ":" + sec;
		}else if (min < 60 && sec < 10) {
			document.getElementById("conta-tempo").innerHTML = min + ":0" + sec;
		}else if (min < 60 && sec < 60) {
			document.getElementById("conta-tempo").innerHTML = min + ":" + sec;
		}
	}
}

var clock = setInterval(conta_seg, 1000);
<div id="conta-tempo"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.