Skip to content

Instantly share code, notes, and snippets.

@bantic
Created April 15, 2025 08:57
Show Gist options
  • Save bantic/a1e65c2d31335b3f51c869ebe0f55710 to your computer and use it in GitHub Desktop.
Save bantic/a1e65c2d31335b3f51c869ebe0f55710 to your computer and use it in GitHub Desktop.
simple html timer
<html>
<body>
<style>
.container {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
flex-direction: column;
}
.timer {
font-size: 100px;
font-family: math;
}
</style>
<div class="container">
<div class="timer"></div>
<div class="controls">
<button id="start">Start</button>
<button id="reset">Reset</button>
<button id="stop">Stop</button>
</div>
</div>
<script>
document.getElementById("start").addEventListener("click", startTimer);
document.getElementById("reset").addEventListener("click", resetTimer);
document.getElementById("stop").addEventListener("click", stopTimer);
let startAt = new Date();
let state = "stopped";
let elapsed = 0;
function updateElapsed() {
if (state === "started") {
elapsed = Math.floor((new Date() - startAt) / 1000);
}
}
function render() {
updateElapsed();
const timerElement = document.querySelector(".timer");
const minutes = Math.floor(elapsed / 60);
const seconds = elapsed % 60;
timerElement.textContent = `${minutes}:${
seconds < 10 ? "0" : ""
}${seconds}`;
requestAnimationFrame(render);
}
render();
function startTimer() {
startAt = new Date();
state = "started";
}
function stopTimer() {
state = "stopped";
}
function resetTimer() {
elapsed = 0;
state = "stopped";
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment