Skip to content

Instantly share code, notes, and snippets.

@MizR
Last active April 30, 2024 11:10
Show Gist options
  • Save MizR/86bbe0a8b2d5a29097271312960d23e3 to your computer and use it in GitHub Desktop.
Save MizR/86bbe0a8b2d5a29097271312960d23e3 to your computer and use it in GitHub Desktop.
Untitled
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
</head>
<body>
<h1>Countdown Timer</h1>
<div id="timer"></div>
</body>
</html>
function setCountdown() {
const now = new Date().getTime();
const storedEndTime = localStorage.getItem("eTime");
// Check if there's a stored end time and it's still in the future
let endTime;
if (storedEndTime && now < storedEndTime) {
endTime = storedEndTime;
} else {
// Set new end time for 3 days from now
endTime = now + 60000; // 3 days in milliseconds
localStorage.setItem("eTime", endTime);
}
// Update the countdown every second
const interval = setInterval(function() {
const now = new Date().getTime();
const timeLeft = endTime - now;
// Time calculations for days, hours, minutes, and seconds
const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
// Output the result in the timer div
document.getElementById("timer").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the countdown is over, clear interval and reset
if (timeLeft < 0) {
clearInterval(interval);
localStorage.removeItem("Time");
setCountdown(); // Restart the countdown
document.getElementById("timer").innerHTML = "loading...";
}
}, 1000);
}
setCountdown();
{"view":"split","fontsize":"100","seethrough":"","prefixfree":"1","page":"javascript"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment