Beispiel:JS-Timer-2.html
Aus SELFHTML-Wiki
<!doctype html> <html lang="de"> <head>
<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css"> <title>Timer 2 - Countdown</title>
<style> p{
border: medium solid; border-radius: 50%; width: 3em; margin-left: 2em; padding: 2em 1em; text-align: center;
} </style> <script> 'use strict'; document.addEventListener('DOMContentLoaded', function () {
const duration = 15;
document.querySelector('#start').addEventListener(
'click',
function() { // anonyme Funktion timer(duration); }, false
);
function timer(duration) {
const startTime = Date.now(); const targetTime = startTime + (duration * 1000);
let interval = setInterval(function() { let elapsedTime = targetTime - Date.now();
if (elapsedTime > 0) {
document.getElementById('timer').textContent = (elapsedTime / 1000).toFixed(1);
} else { clearInterval(interval); document.getElementById('timer').textContent = "0.0"; console.log("Countdown finished!"); } }, 100);
}
}); </script> </head>
<body>
Timer 2 - Countdown
<button type="button" id="start">Start!</button>
<output id="timer"></output> s
</body> </html>