setTimeout: raz, po czasie
Timery i daty - JavaScript na stronach WWW (HTML/CSS/JS)
`setTimeout(funkcja, ms)` wykona funkcję raz, po podanej liczbie milisekund, a kod pod nim działa dalej od razu (nie czeka). Zwraca numer, którym `clearTimeout` może odwołać wykonanie. Kliknij "Przypomnij" i zdąż kliknąć "Odwołaj" przed upływem 2 sekund.
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<title>setTimeout</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>
<button id="remind">Przypomnij za 2 s</button>
<button id="cancel">Odwołaj</button>
<p id="msg"></p>
<script>
let timer = null;
const msg = document.getElementById('msg');
document.getElementById('remind').addEventListener('click', () => {
clearTimeout(timer);
msg.textContent = 'Czekam...';
timer = setTimeout(() => {
msg.textContent = 'Przypomnienie: weź plecak!';
timer = null;
}, 2000);
msg.textContent += ' (ten tekst ustawił kod tuż po setTimeout)';
});
document.getElementById('cancel').addEventListener('click', () => {
if (timer === null) return;
clearTimeout(timer);
timer = null;
msg.textContent = 'Odwołane';
});
</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.