This code is meant to start a timer when you type something into the text input, that will count every second until it reaches 5 seconds, and then stop. But it keeps spitting out 0 which is creating an endless while loop that crashes the browser. I'm sure I'm missing something obvious here :-/ !?
var secondsPassed = 0;
function setTimer() {
while (secondsPassed <= 5) {
console.log(secondsPassed);
setInterval(function() { secondsPassed += 1; }, 1000);
}
}
<input type="text" onkeyup="setTimer()">
It's the wrong way to both set the interval and count time.
I recommend something on the lines of:
var secondsPassed = 0, timerOn = false;
function setTimer(){
if(timerOn) return;
var t0 = Date.now();
timerOn = true;
var intervalId = setInterval(
function(){
secondsPassed = Math.round((Date.now()-t0)/1000);
console.log(secondsPassed)
if(secondsPassed >= 10){
clearInterval(intervalId);
timerOn = false;
}
}, 1000
);
}
<input type="text" onkeyup="setTimer()">
I stopped the timer after 10 seconds, for the case someone wants to test it, but of course, you'll have to stop it otherwise.
Your while loop will never stop because its condition (secondsPassed <= 5) will never evaluate to true, since setInterval isn't synchronous.
You should instead move the condition inside the setInterval.
var secondsPassed = 0;
function setTimer() {
var interval = setInterval(function() {
if (++secondsPassed == 5) clearInterval(interval);
console.log(secondsPassed)
}, 1000);
}
<input type="text" onkeyup="setTimer()">