24 Javascript timer dont run - javascript

Hey I try to run the timer always until 24 o'clock but it always runs 24 when the page is loaded. I do not understand how I can calculate that the timer always shows the correct time until 24 o'clock can someone help me?
const countToDate = new Date().setHours(new Date().getHours() + 24)
let previousTimeBetweenDates
setInterval(() => {
const currentDate = new Date()
const timeBetweenDates = Math.ceil((countToDate - currentDate) / 1000)
flipAllCards(timeBetweenDates)
previousTimeBetweenDates = timeBetweenDates
}, 250)
function flipAllCards(time) {
const seconds = time % 60
const minutes = Math.floor(time / 60) % 60
const hours = Math.floor(time / 3600)
flip(document.querySelector("[data-hours-tens]"), Math.floor(hours / 10))
flip(document.querySelector("[data-hours-ones]"), hours % 10)
flip(document.querySelector("[data-minutes-tens]"), Math.floor(minutes / 10))
flip(document.querySelector("[data-minutes-ones]"), minutes % 10)
flip(document.querySelector("[data-seconds-tens]"), Math.floor(seconds / 10))
flip(document.querySelector("[data-seconds-ones]"), seconds % 10)
}
function flip(flipCard, newNumber) {
const topHalf = flipCard.querySelector(".top")
const startNumber = parseInt(topHalf.textContent)
if (newNumber === startNumber) return
const bottomHalf = flipCard.querySelector(".bottom")
const topFlip = document.createElement("div")
topFlip.classList.add("top-flip")
const bottomFlip = document.createElement("div")
bottomFlip.classList.add("bottom-flip")
top.textContent = startNumber
bottomHalf.textContent = startNumber
topFlip.textContent = startNumber
bottomFlip.textContent = newNumber
topFlip.addEventListener("animationstart", e => {
topHalf.textContent = newNumber
})
topFlip.addEventListener("animationend", e => {
topFlip.remove()
})
bottomFlip.addEventListener("animationend", e => {
bottomHalf.textContent = newNumber
bottomFlip.remove()
})
flipCard.append(topFlip, bottomFlip)
}

Related

How to display year in jQuery countdown timer

I have a countdown timer for next 25 years. how can I display years in this timer. currently instead of year days are showing. I need to display the years also. please help .
enter image description here
please find the code i have used
"code"
enter code here
let daysItem = document.querySelector("#days");
let hoursItem = document.querySelector("#hours");
let minItem = document.querySelector("#min");
let secItem = document.querySelector("#sec");
let countDown = () => {
let futureDate = new Date("17 august 2022 9:59:59");
let currentDate = new Date();
let myDate = futureDate - currentDate;
//console.log(myDate);
let days = Math.floor(myDate / 1000 / 60 / 60 / 24);
let hours = Math.floor(myDate / 1000 / 60 / 60) % 24;
let min = Math.floor(myDate / 1000 / 60) % 60;
let sec = Math.floor(myDate / 1000) % 60;
daysItem.innerHTML = days;
hoursItem.innerHTML = hours;
minItem.innerHTML = min;
secItem.innerHTML = sec;
}
countDown()
setInterval(countDown, 1000)
You need to make calculation with getFullYear() from current date to futur date.
let yearsItem = document.querySelector("#years");
let daysItem = document.querySelector("#days");
let hoursItem = document.querySelector("#hours");
let minItem = document.querySelector("#min");
let secItem = document.querySelector("#sec");
let countDown = () => {
let futureDate = new Date("17 august 2047 9:59:59");
let currentDate = new Date();
let myDate = futureDate - currentDate;
//console.log(myDate);
let years = futureDate.getFullYear() - currentDate.getFullYear();
let days = Math.floor(myDate / 1000 / 60 / 60 / 24);
let hours = Math.floor(myDate / 1000 / 60 / 60) % 24;
let min = Math.floor(myDate / 1000 / 60) % 60;
let sec = Math.floor(myDate / 1000) % 60;
yearsItem.innerHTML = years;
daysItem.innerHTML = days;
hoursItem.innerHTML = hours;
minItem.innerHTML = min;
secItem.innerHTML = sec;
}
countDown()
setInterval(countDown, 1000)
div { display:inline-block; padding:5px; background:#000; color:#fff }
Years <div id="years"></div>
Days <div id="days"></div>
Hours <div id="hours"></div>
Min <div id="min"></div>
Sec <div id="sec"></div>

Timer continues after 0

I made a timer for a project in school (I am still in school yes and I do not have JavaScript as a lesson that we get this semester) in JavaScript and it continues after the 0. I got some help from a teacher but I can't reach him with the pandemic and stuff.
This is the code that I wrote and what happens is that when it reaches the date that I put in it goes into -0 -0 -0 -01 and continues from there.
const countdown = () => {
let countDate = new Date('Febuary 9, 2022 00:00:00').getTime();
let now = new Date().getTime();
let gap = countDate - now;
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
let textDay = Math.floor(gap / day);
let textHour = Math.floor((gap % day) / hour);
let textMinute = Math.floor((gap % hour) / minute);
let textSecond = Math.floor((gap % minute) / second);
document.querySelector('.day').innerText = textDay;
document.querySelector('.hour').innerText = textHour;
document.querySelector('.minute').innerText = textMinute;
document.querySelector('.second').innerText = textSecond;
};
setInterval(countdown, 1000);
setInterval returns a value which you can pass to clearInterval to stop the interval from running. Store that value in a variable, for example:
let countInterval = 0;
const countdown = () => {
//...
};
countInterval = setInterval(countdown, 1000);
Then within countdown you can check if you want to clear that interval. For example, if you want to clear it when gap <= 0 you would perform that logic:
if (gap <= 0) {
clearInterval(countInterval);
return;
}
This would stop the interval from running when that condition is eventually met.
Example:
let countInterval = 0;
const countdown = () => {
let countDate = new Date('January 11, 2022 13:35:00').getTime();
let now = new Date().getTime();
let gap = countDate - now;
if (gap <= 0) {
clearInterval(countInterval);
return;
}
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
let textDay = Math.floor(gap / day);
let textHour = Math.floor((gap % day) / hour);
let textMinute = Math.floor((gap % hour) / minute);
let textSecond = Math.floor((gap % minute) / second);
document.querySelector('.day').innerText = textDay;
document.querySelector('.hour').innerText = textHour;
document.querySelector('.minute').innerText = textMinute;
document.querySelector('.second').innerText = textSecond;
};
countInterval = setInterval(countdown, 1000);
<div class="day"></div>
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>

How do you create a 12hour time in JavaScript

I would like to have a timer where it does something after 12 hours. I would like to begin at 6am and end at 6pm. The time only needs to be for 12 hours. I would like to know how I can adjust the time. What I would like to do is convert my current 12-hour clock into 24 hours.
I'm looking for working examples
The code example is in this CodePen link
Timer Link
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let birthday = "Nov 25, 2020 00:00:00",
countDown = new Date(birthday).getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = countDown - now;
document.getElementById("days").innerText = Math.floor(distance / (day)),
document.getElementById("hours").innerText = Math.floor((distance % (day)) / (hour)),
document.getElementById("minutes").innerText = Math.floor((distance % (hour)) / (minute)),
document.getElementById("seconds").innerText = Math.floor((distance % (minute)) / second);
//do something later when date is reached
if (distance < 0) {
let headline = document.getElementById("headline"),
countdown = document.getElementById("countdown"),
content = document.getElementById("content");
headline.innerText = "It's my birthday!";
countdown.style.display = "none";
content.style.display = "block";
clearInterval(x);
}
//seconds
}, 0)
}());
I would use Luxon.js:
npm install luxon
Then, it's an easy...
const {DateTime, Duration} = require('luxon');
function countdown(zeroDate) {
const zero = DateTime.fromISO(zeroDate);
const timer = setInterval(function() {
const delta = zero
.diff(DateTime.local())
.shiftTo('days', 'hours', 'minutes', 'seconds', 'milliseconds');
const {days: d, hours: h, minutes: m, seconds: s} = delta;
if ( delta.valueOf() < 1 ) {
console.log("Happy Birthday!");
clearInterval(timer);
} else {
console.log(`${d}d ${h}h ${m}m ${s}s Remaining`);
}
}, 1000 );
}
If invoked with
const {DateTime, Duration} = require('luxon');
const start = DateTime.local().plus({seconds: 15}).toISO();
countdown(start);
This should work, it will show the time until 8:00 PM when its 8:00 AM. Here's the pen I made to test it Time Until.
var doIt = false;
var now = new Date();
var seconds;
var date1;
var eight = new Date();
eight.setHours(20, 0, 0);
var date2;
var toHHMMSS = (secs) => {
var sec_num = parseInt(secs, 10)
var hours = Math.floor(sec_num / 3600)
var minutes = Math.floor(sec_num / 60) % 60
var seconds = sec_num % 60
return [hours,minutes,seconds]
.map(v => v < 10 ? "0" + v : v)
.filter((v,i) => v !== "00" || i > 0)
.join(":")
}
function diff_seconds(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
return Math.abs(Math.round(diff));
}
window.setInterval(function(){
date2 = new Date();
if(date2.getHours() >= 8) {
doIt = true;
}
}, 1);
window.setInterval(function(){
date2 = new Date();
if(date2.getHours() >= 20){
doIt = false;
}
}, 1);
window.setInterval(function(){
if(doIt === true){
seconds = diff_seconds(new Date(), eight);
document.querySelector("p").textContent = "It is from 8AM to 8PM";
document.querySelector("#hours").textContent = toHHMMSS(seconds);
}
}, 1000)
<p>It is not 8 AM yet</p>
<div id="hours"></div>
Hope it works!

Countdown Timer Ends Meessage

A few days ago, I created countdown timer by watching a video on YouTube. The countdown timer is completely perfect but one thing is missing from it. When the timer goes to the zero it will hide from the page.
I want to show some text when timer ends. Like if timer goes to zero then timer hides and show this message "You are too late. Stay with us".
This is a .js code in which I need some modification.
const dayDisplay = document.querySelector(".days .number");
const hourDisplay = document.querySelector(".hours .number");
const minuteDisplay = document.querySelector(".minutes .number");
const secondDisplay = document.querySelector(".seconds .number");
const countdownContainer = document.querySelector(".countdown-container");
const endDate = new Date("August 04 2020 10:38:00");
let saleEnded = false;
const updateTimer = () => {
if(countdownContainer) {
let currentDate = new Date();
let difference = endDate.getTime() - currentDate.getTime();
if (difference <= 1000) {
saleEnded = true;
}
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
let newDay = Math.floor(difference / day);
let newHour = Math.floor((difference % day) / hour);
let newMiute = Math.floor((difference % hour) / minute);
let newSecond = Math.floor((difference % minute) / second);
dayDisplay.innerText = newDay < 10 ? "0" + newDay : newDay;
hourDisplay.innerText = newHour < 10 ? "0" + newHour : newHour;
minuteDisplay.innerText = newMiute < 10 ? "0" + newMiute : newMiute;
secondDisplay.innerText = newSecond < 10 ? "0" + newSecond : newSecond;
};
};
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
}
}, 1000);
Try this?
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
countdownContainer.innetHTML="You are too late. Stay with us";
}
}, 1000);

JavaScript countdown, formatting seconds to HH:MM:SS

I have a countdown timer that takes 'seconds' and formats it into HH:MM:SS format. The problem is the second shows 60.
Here's the code I have, this is part of a much larger class. Any suggestions on the best way format so that it doesn't use '60' as a second.
Thank you!
formatSeconds: function (seconds) {
secondsRemaining = seconds;
hoursRemaining = Math.floor(secondsRemaining / (60 * 60));
minutesRemaining = secondsRemaining % (60 * 60);
hourMinutesRemaining = Math.floor(minutesRemaining / 60);
minuteSecondsRemaining = minutesRemaining % 60;
hourSecondsRemaining = Math.ceil(minuteSecondsRemaining);
fHrs = this.formatNumber(hoursRemaining);
fMins = this.formatNumber(hourMinutesRemaining);
fSecs = this.formatNumber(hourSecondsRemaining);
return fHrs + ':' + fMins + ':' + fSecs;
},
formatNumber: function (number) {
var s = String(number);
if (s.length == 1) {
s = '0' + s;
}
return s;
}
Update: this is a new version of the previous function. I noticed a bug in the previous version due to floating point rounding errors when the number of seconds was near an hour or minute boundary. Conceptually the math was correct but practically speaking it wasn't when using IEEE-754 number precision.
Here is the function I have written that I use in my code for this purpose:
const formatSeconds = (secs) => {
const pad = (n) => n < 10 ? `0${n}` : n;
const h = Math.floor(secs / 3600);
const m = Math.floor(secs / 60) - (h * 60);
const s = Math.floor(secs - h * 3600 - m * 60);
return `${pad(h)}:${pad(m)}:${pad(s)}`;
}
Demo
// Test harness
const demo = () => {
var seconds = 36005;
var $output = document.querySelector('.output');
return () => {
if (seconds >= 0) {
$output.innerHTML = `${formatSeconds(seconds)} (${seconds} seconds)`;
seconds--;
}
};
}
setInterval(demo(), 1000);
// The function
const formatSeconds = (secs) => {
const pad = (n) => n < 10 ? `0${n}` : n;
const h = Math.floor(secs / 3600);
const m = Math.floor(secs / 60) - (h * 60);
const s = Math.floor(secs - h * 3600 - m * 60);
return `${pad(h)}:${pad(m)}:${pad(s)}`;
}
<div class="output"></div>
Test code
This is a basic test a wrote to validate that this new function works without edge cases.
const formatSeconds = (secs) => {
const pad = (n) => n < 10 ? `0${n}` : n;
const h = Math.floor(secs / 3600);
const m = Math.floor(secs / 60) - (h * 60);
const s = Math.floor(secs - h * 3600 - m * 60);
return `${pad(h)}:${pad(m)}:${pad(s)}`;
}
const countSeconds = (str) => {
const parts = str.split(':');
const h = parseInt(parts[0], 10);
const m = parseInt(parts[1], 10);
const s = parseInt(parts[2], 10);
return h * 3600 + m * 60 + s;
}
const compare = (secs) => secs === countSeconds(formatSeconds(secs));
var falses = 0;
for (let i = 0; i < 999999; i++) {
if (compare(i) === false) {
falses++;
console.log(`Error: ${i} Seconds`);
}
}
console.log(`${falses} errors`);
Slight modification to pseudosavant's solution as we don't want the timer to hang on 00:00 for a second while the timer is still running:
var s;
if(h === 0 && m === 0) {
// last minute only has 59 seconds
s = Math.ceil((secs / 60) % 1 * 59);
}
else {
s = Math.floor((secs / 60) % 1 * 60);
}

Categories