'Error with count up when use setInterval and clearInterval
I use countTime function for incrementing timer, I have 1 function gameStart to initialize game structures and assign variable totalSecond = 0 and variable timeStart = setInterval(countTime, 1000). I have a button that when clicked it will run the function gameStart. When I run the code for the first time, everything is fine, but when I press the button many times with the newGame event, it increases the time very quickly. I have to clearInteval when I lose the game so time can stop. Thank for help me
function countTimer() {
totalSeconds++;
var hour = Math.floor(totalSeconds /3600);
var minute = Math.floor((totalSeconds - hour*3600)/60);
var seconds = totalSeconds - (hour*3600 + minute*60);
if(hour < 10)
hour = "0"+hour;
if(minute < 10)
minute = "0"+minute;
if(seconds < 10)
seconds = "0"+seconds;
document.getElementById("countUp").innerHTML = hour + ":" + minute + ":" + seconds;
}
function gameStart() {
timerVar = setInterval(countTimer, 1000);
totalSeconds = 0;
rows = parseInt(document.getElementById("rows").value);
cols = parseInt(document.getElementById("cols").value);
mineCount = parseInt(document.getElementById("mines").value);
rows = rows > 10 ? rows : 10;
cols = cols > 10 ? cols : 10;
mCount = mCount > 10 ? mCount : 10;
openedCells=0;
initBoard();
initHTML();
}
Solution 1:[1]
setInterval functions never expire until you call clearInterval. In your case, every time you run gameStart, a new interval is created that counts up. You are left with multiple intervals, making the timer go up quicker and quicker.
A quick fix would be to declare timerVar outside the Function, then clear and re-make it every time gameStart is called.
timerVar = setInterval(()=>{},1000) // Empty interval
function gameStart() {
clearInterval(timerVar)
timerVar = setInterval(countTimer, 1000);
totalSeconds = 0;
I'm unable to test this at the moment, but it should work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | codingmaster398 |
