Last active
April 15, 2023 16:12
-
-
Save pedrominicz/8790f957353ee2825af2477b79cd7450 to your computer and use it in GitHub Desktop.
Simple Javascript timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<title>Timer</title> | |
<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII="> | |
<style type="text/css"> | |
body { | |
background-color: #111; | |
color: #bbb; | |
text-align: center; | |
} | |
h1 { | |
font-size: 90px; | |
} | |
</style> | |
</head> | |
<body> | |
<h1 id="timer">00:00</h1> | |
<script type="text/javascript"> | |
'use strict' | |
const timer = document.getElementById('timer') | |
const duration = 1500 | |
let seconds = duration | |
function show() { | |
const m = Math.floor(seconds / 60) | |
const s = seconds % 60 | |
timer.innerText = `${m < 10 ? '0' : ''}${m}:${s < 10 ? '0' : ''}${s}` | |
} | |
show() | |
let interval = null | |
function start() { | |
seconds = duration | |
show() | |
interval = setInterval(update, 1000) | |
} | |
addEventListener('click', () => { | |
start() | |
update() | |
}, {once: true}) | |
function update() { | |
if (seconds < 1) { | |
end() | |
return | |
} | |
--seconds | |
show() | |
} | |
function end() { | |
clearInterval(interval) | |
const audio = new AudioContext() | |
const volume = audio.createGain() | |
volume.connect(audio.destination) | |
volume.gain.value = 0.05 | |
const oscillator = audio.createOscillator() | |
oscillator.start() | |
let connected = false | |
interval = setInterval(() => { | |
if (connected) { | |
oscillator.disconnect(volume) | |
timer.style.color = null | |
connected = false | |
} else { | |
oscillator.connect(volume) | |
timer.style.color = '#4b4' | |
connected = true | |
} | |
}, 500) | |
addEventListener('click', () => { | |
clearInterval(interval) | |
if (connected) { | |
oscillator.disconnect(volume) | |
timer.style.color = null | |
connected = false | |
} | |
start() | |
}, {once: true}) | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment