A New Year countdown subtracts the current timestamp from the next January 1 target and converts the remaining milliseconds into days, hours, minutes and seconds. Recalculate from the fixed target each tick instead of subtracting one second from a counter.
const now = new Date();
const target = new Date(now.getFullYear() + 1, 0, 1);
const remaining = target.getTime() - Date.now();
The numeric Date constructor creates a local date. Month 0 means January.
const now = new Date();
const newYear = new Date(
now.getFullYear() + 1,
0,
1,
0,
0,
0,
0
);
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;
const hh = String(hours).padStart(2, "0");
const mm = String(minutes).padStart(2, "0");
const ss = String(seconds).padStart(2, "0");
Stop or reset the timer when the target is reached. If the page stays open after midnight, calculate the following year's target rather than allowing a negative countdown.
if (remaining <= 0) {
output.textContent = "Happy New Year!";
clearInterval(timerId);
}
The numeric constructor above targets midnight in the visitor's local time zone. If the event belongs to a specific region, define the intended instant explicitly or calculate it with a time-zone-aware approach. A New York New Year and an India New Year are different instants.
setInterval(..., 1000) does not guarantee exact one-second execution. Recalculate target - Date.now() every tick, so a delayed callback does not permanently make the countdown late.
You do not need to wait until New Year. Use a target a few seconds in the future.
const target = new Date(Date.now() + 10000);
10-second test demo General countdown timer
Related: JavaScript Date and JavaScript clock.
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.