Show sourcecode
The following files exists in this folder. Click to view.
public_html/gamla-kurser/webbutv2/övningar/js_timers/
js_timers_a.html
js_timers_b.html
js_timers_c.html
js_timers_d.html
js_timers_e.html
js_timers_f.html
js_timers_g.html
js_timers_h.html
js_timers_i.html
js_timers_j.html
sound/
js_timers_e.html
72 lines UTF-8 Windows (CRLF)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Timers E</title>
</head>
<body>
<h1>JS Timers E</h1>
<button onclick="toggleTimer()" id="startButton">Start</button>
<button onclick="resetTimer()">Reset</button>
<br>
<h2>Välj minuter och sekunder för nedräkning</h2>
<input type="time" id="timeInput" step="1">
<h2 id="timer">Timer: 0 timmar 0 minuter och 0 sekunder kvar.</h2>
<h2 id="text"></h2>
<script>
let timer = document.getElementById("timer");
let text = document.getElementById("text");
let button = document.getElementById("startButton");
let timeInput = document.getElementById("timeInput");
let count = 0;
let currentInterval = 1000;
let active = false;
let intervalId;
function myTimer() {
if (count <= 0) {
clearInterval(intervalId);
timer.innerHTML = "Timer: 0 timmar 0 minuter och 0 sekunder kvar.";
button.innerHTML = "Start";
active = false;
return;
}
count--;
let hours = Math.floor(count / 3600);
let minutes = Math.floor((count % 3600) / 60);
let seconds = count % 60;
timer.innerHTML = `Timer: ${hours} timmar ${minutes} minuter och ${seconds} sekunder kvar.`;
}
function toggleTimer() {
if (active) {
clearInterval(intervalId);
button.innerHTML = "Start";
} else {
if (count === 0) {
let timeParts = timeInput.value.split(":");
let hours = parseInt(timeParts[0]);
let minutes = parseInt(timeParts[1]);
let seconds = parseInt(timeParts[2]);
count = hours * 3600 + minutes * 60 + seconds;
}
intervalId = setInterval(myTimer, currentInterval);
button.innerHTML = "Pausa";
}
active = !active;
}
function resetTimer() {
clearInterval(intervalId);
count = 0;
timer.innerHTML = "Timer: 0 timmar 0 minuter och 0 sekunder kvar.";
active = false;
button.innerHTML = "Start";
}
</script>
</body>
</html>