आप जावास्क्रिप्ट में setInterval मेथड का उपयोग करके काउंटडाउन टाइमर बना सकते हैं। setInterval() मेथड एक फंक्शन को बार-बार कॉल करता है या एक कोड स्निपेट एक्जीक्यूट करता है, प्रत्येक कॉल के बीच एक निश्चित समय देरी के साथ।
काउंटडाउन बनाने के लिए, हमें वर्तमान समय और अंतिम समय के बीच का अंतर चेक करना होगा और काउंटडाउन को अपडेट करते रहना होगा।
उदाहरण
let countDownDate = new Date("Jul 21, 2020 00:00:00").getTime();
let x = setInterval(() => {
let now = new Date().getTime();
let distance = countDownDate - now;
// दिन, घंटे, मिनट, सेकंड के लिए समय गणना
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s");
// यदि काउंटडाउन समाप्त हो गया
if (distance < 0) {
clearInterval(x);
console.log("completed");
}
}, 1000);
आउटपुट
310d 0h 6m 46s
310d 0h 6m 45s
310d 0h 6m 44s
...
पुन: उपयोग करने योग्य काउंटडाउन कंपोनेंट
function createCountdown(targetDate, onTick, onComplete) {
const interval = setInterval(() => {
const now = Date.now();
const distance = targetDate - now;
if (distance < 0) {
clearInterval(interval);
onComplete?.();
return;
}
const time = {
days: Math.floor(distance / 86400000),
hours: Math.floor((distance % 86400000) / 3600000),
minutes: Math.floor((distance % 3600000) / 60000),
seconds: Math.floor((distance % 60000) / 1000),
total: distance
};
onTick(time);
}, 1000);
return () => clearInterval(interval); // क्लीनअप फंक्शन
}
// उपयोग
const stop = createCountdown(
new Date('2024-12-31').getTime(),
(time) => console.log(`${time.days}d ${time.hours}h ${time.minutes}m ${time.seconds}s`),
() => console.log('नया साल मुबारक!')
);
requestAnimationFrame के साथ (स्मूथर)
function smoothCountdown(targetDate, callback) {
function tick() {
const distance = targetDate - Date.now();
if (distance <= 0) {
callback({ days: 0, hours: 0, minutes: 0, seconds: 0 });
return;
}
callback({
days: Math.floor(distance / 86400000),
hours: Math.floor((distance % 86400000) / 3600000),
minutes: Math.floor((distance % 3600000) / 60000),
seconds: Math.floor((distance % 60000) / 1000)
});
requestAnimationFrame(tick);
}
tick();
}