A JavaScript countdown calculates the difference between a fixed target timestamp and the current time, then converts that remaining duration into days, hours, minutes, and seconds. Recalculate from timestamps on every update so page delays do not make the countdown drift.
const remaining = targetTime - Date.now();
const targetTime = new Date("2027-01-01T00:00:00+05:30").getTime();
Use an explicit offset or time-zone-aware server value when the event happens at a specific real-world instant.
const remaining = Math.max(0, targetTime - Date.now());
const totalSeconds = Math.floor(remaining / 1000);
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor((totalSeconds % 86400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
See Math.floor() for integer rounding.
function updateCountdown() {
const remaining = Math.max(0, targetTime - Date.now());
output.textContent = formatRemaining(remaining);
}
const id = setInterval(updateCountdown, 1000);
updateCountdown();
if (remaining <= 0) {
clearInterval(id);
output.textContent = "Event started";
}
Do not store only “86,501 seconds remaining” in the page and decrement it. Store or calculate the absolute event timestamp. After a refresh, calculate the difference again. The older downloadable countdown source and fixed-target countdown example illustrate the same general requirement, but the timestamp approach is more robust.
A countdown is easiest when the target is a precise instant. If users enter a local calendar date/time, decide which time zone that input belongs to and make that rule explicit. An ambiguous string can represent different instants on different systems.
Intervals may run late, especially in inactive tabs. Because each display refresh subtracts Date.now() from the fixed target, a late callback does not permanently accumulate one-second errors.
Cross-language references from the original page: PHP tutorials and ASP tutorials.
Related: real-time clock, setTimeout(), stopwatch, and setting input focus.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| emmanuel ogbonnaya smith | 02-08-2012 |
| hello, can any body help me out. really am running a hotspot internet cafe , and am using a mikrotik os for my hotspot. really i want to display time left for my client on there computers, or laptop, i dont know to do that . can someone help me out thank u | |
12-08-2020 | |
| how to code this when I refresh the page the time remaining will not returning back to the time? | |
23-08-2020 | |
| This part is explained now and one demo page is added. HTH | |