I'm trying to make a simple countup timer with a start/stop button. I don't understand why the while loop crashes the page even though it has a 1sec delay. Is there a easier way to keep updating the time until I press the button?
let startButton = document.getElementById("btn-start-stop");
let timerOutput = document.getElementById("timer");
let runTimer = false;
let sec = 0;
let startTimer = false;
console.log(startTimer);
startButton.onclick = function () {
startTimer = !startTimer;
while (startTimer) {
setInterval(function () {
console.log(sec);
}, 1000);
}
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="an exercise to manipulate DOM-elements">
<meta name="author" content="lars berg">
<meta name="keywords" content="a template for at exercise">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>DOM | Manipulate</title>
<script src="https://kit.fontawesome.com/fa41e523cd.js" crossorigin="anonymous"></script>
<script src="scripts/script.js" defer></script>
</head>
<body>
<header>
<h1>DOM | Manipulation</h1>
</header>
<main>
<div class="flex-container">
<div class="counter-container">
<h2 class="h2-counter">How long time will it take to read this information?</h2>
<div id="timer">
00:00:00
</div>
<div class="buttons">
<button id="btn-start-stop" type="button">
<i class="fa-solid fa-play fa-2x"></i>
</button>
<button id="btn-reset" type="button">
<i class="fa-solid fa-arrow-rotate-left fa-2x"></i>
</button>
</div>
</div>
</div>
</main>
<footer>
</footer>
</body>
</html>