Stoper krok 2: czas z Date.now()
Timery i daty - JavaScript na stronach WWW (HTML/CSS/JS)
Poprawka: interwał tylko odświeża ekran, a czas liczy zegar systemu. `Date.now()` zwraca milisekundy od 1970 roku, więc czas stopera to różnica między teraz a chwilą startu (plus czas z wcześniejszych odcinków po pauzie). Opóźnione tyknięcie nie gubi czasu, a `timer !== null` blokuje podwójny start. Przyciski są włączane i wyłączane zgodnie ze stanem.
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<title>Stoper</title>
<style>
body { font-family: sans-serif; max-width: 36em; line-height: 1.4; }
input, select, button, textarea { font: inherit; padding: 0.2em 0.4em; }
table { border-collapse: collapse; }
th, td { border: 1px solid #94a3b8; padding: 0.2em 0.6em; }
</style>
</head>
<body>
<p id="time">0.0 s</p>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Zeruj</button>
<script>
let timer = null;
let startedAt = 0;
let saved = 0;
const elapsed = () => saved + (timer === null ? 0 : Date.now() - startedAt);
function show() {
document.getElementById('time').textContent = (elapsed() / 1000).toFixed(1) + ' s';
document.getElementById('start').disabled = timer !== null;
document.getElementById('stop').disabled = timer === null;
}
document.getElementById('start').addEventListener('click', () => {
if (timer !== null) return;
startedAt = Date.now();
timer = setInterval(show, 100);
show();
});
document.getElementById('stop').addEventListener('click', () => {
if (timer === null) return;
saved = elapsed();
clearInterval(timer);
timer = null;
show();
});
document.getElementById('reset').addEventListener('click', () => {
saved = 0;
startedAt = Date.now();
show();
});
show();
</script>
</body>
</html>Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu JavaScript na stronach WWW·Zaloguj się, aby zapisać postęp na koncie.