Search code examples
javascripteventstimersetintervalstopwatch

Lag on count up timer starting


Building a simple count up timer in JavaScript. When I click the start button there is a lag between when the button is clicked and the timer starts. Can someone please explain why this is. I am a beginner to JavaScript so I clear and simple to understand explanation would be really appreciated.

Thank you in advance

var startButton = document.getElementById("start");
var pauseButton = document.getElementById("pause");
var resetButton = document.getElementById("reset");
var minutesHTML = document.getElementById("minutes");
var secondsHTML = document.getElementById("seconds");
var seconds = 00;
var minutes = 00;
var myTimer = false;


startButton.onclick = startTimer;
pauseButton.onclick = pauseTimer;
resetButton.onclick = resetTimer;

function startTimer () {
	
	myTimer = setInterval (function () {
		
		if (seconds < 10) {
			secondsHTML.innerHTML = "0" + seconds;
		}
		if (seconds > 9) {
			secondsHTML.innerHTML = seconds;
		}
		
		
		seconds ++;
		
		if (seconds % 60 == 0) {
			minutes ++;
			seconds = 00;
		}
		
		if (minutes < 10) {
			minutesHTML.innerHTML = "0" + minutes;
		}
		
		if (minutes >= 10) {
			minutesHTML.innerHTML = minutes;
		}
		
	}		
	, 1000)
}


function pauseTimer () {
	clearInterval(myTimer);
}

function resetTimer () {
	seconds = 00;
	minutes = 00;
	secondsHTML.innerHTML = seconds;
	minutesHTML.innerHTML = minutes;
	
	console.log(secondsHTML + minutesHTML);
	clearInterval(myTimer);

}
body{
	background: tomato;
	text-align: center;
	margin: auto;
	font-size: 50px;
}

h1 {
	font-size: 20px;
}

.button-container {
	display: flex;
	margin: auto;
}

button {
	text-align: center;
	border: none;
	width: 20%;
	background: #fff;
	font-size: 20px;
	margin: auto;
}
<h1>TIMER</h1>


<p>
	<span id="minutes">00</span>
	:
	<span id="seconds">00</span>
</p>


<div class="button-container">
<button id="start"><p>START</p></button>
<button id = "pause"><p>PAUSE</p></button>
<button id = "reset"><p>RESET</p></button>
</div>


Solution

  • setInterval waits until an interval (1000ms in your code) has passed before it runs your function for the first time.

    You could call the function yourself right before you call setInterval. That way you get one immediate call, then one every second until the interval is cancelled.

    function tick () {
    
        if (seconds < 10) {
            secondsHTML.innerHTML = "0" + seconds;
        }
        if (seconds > 9) {
            secondsHTML.innerHTML = seconds;
        }
    
    
        seconds ++;
    
        if (seconds % 60 == 0) {
            minutes ++;
            seconds = 00;
        }
    
        if (minutes < 10) {
            minutesHTML.innerHTML = "0" + minutes;
        }
    
        if (minutes >= 10) {
            minutesHTML.innerHTML = minutes;
        }
    
    }
    
    function startTimer () {
        tick();   
        myTimer = setInterval(tick, 1000);
    }