Timer continues after 0 - javascript

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>

Related

24 Javascript timer dont run

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)
}

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>

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);

Find elapsed time in javascript

I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged in to the current time.
Here is my code:-
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var markMinutes = markDate.getMinutes();
var markSeconds = markDate.getSeconds();
var currDate = new Date();
var currMinutes = currDate.getMinutes();
var currSeconds = currDate.getSeconds();
var minutes = currMinutes - markMinutes;
if(minutes < 0) { minutes += 60; }
var seconds = currSeconds - markSeconds;
if(seconds < 0) { seconds += 60; }
if(minutes < 10) { minutes = "0" + minutes; }
if(seconds < 10) { seconds = "0" + seconds; }
var hours = 0;
if(minutes == 59 && seconds == 59) { hours++; }
if(hours < 10) { hours = "0" + hours; }
var timeElapsed = hours+':'+minutes+':'+seconds;
document.getElementById("timer").innerHTML = timeElapsed;
setTimeout(function() {updateClock()}, 1000);
}
The output is correct upto 00:59:59 but after that that O/P is:
00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00
How can I solve this and is there a more efficient way I can do this?
Thank you.
No offence, but this is massively over-enginered. Simply store the start time when the script first runs, then subtract that from the current time every time your timer fires.
There are plenty of tutorials on converting ms into a readable timestamp, so that doesn't need to be covered here.
var start = Date.now();
setInterval(function() {
document.getElementById('difference').innerHTML = Date.now() - start;
// the difference will be in ms
}, 1000);
<div id="difference"></div>
There's too much going on here.
An easier way would just be to compare markDate to the current date each time and reformat.
See Demo: http://jsfiddle.net/7e4psrzu/
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var currDate = new Date();
var diff = currDate - markDate;
document.getElementById("timer").innerHTML = format(diff/1000);
setTimeout(function() {updateClock()}, 1000);
}
function format(seconds)
{
var numhours = parseInt(Math.floor(((seconds % 31536000) % 86400) / 3600),10);
var numminutes = parseInt(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60),10);
var numseconds = parseInt((((seconds % 31536000) % 86400) % 3600) % 60,10);
return ((numhours<10) ? "0" + numhours : numhours)
+ ":" + ((numminutes<10) ? "0" + numminutes : numminutes)
+ ":" + ((numseconds<10) ? "0" + numseconds : numseconds);
}
markPresent();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="timer"></div>
Here is a solution I just made for my use case. I find it is quite readable. The basic premise is to simply subtract the timestamp from the current timestamp, and then divide it by the correct units:
const showElapsedTime = (timestamp) => {
if (typeof timestamp !== 'number') return 'NaN'
const SECOND = 1000
const MINUTE = 1000 * 60
const HOUR = 1000 * 60 * 60
const DAY = 1000 * 60 * 60 * 24
const MONTH = 1000 * 60 * 60 * 24 * 30
const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
// const elapsed = ((new Date()).valueOf() - timestamp)
const elapsed = 1541309742360 - timestamp
if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s`
if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m`
if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h`
if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d`
if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo`
return `${Math.round(elapsed / YEAR)}y`
}
const createdAt = 1541301301000
console.log(showElapsedTime(createdAt + 5000000))
console.log(showElapsedTime(createdAt))
console.log(showElapsedTime(createdAt - 500000000))
For example, if 3000 milliseconds elapsed, then 3000 is greater than SECONDS (1000) but less than MINUTES (60,000), so this function will divide 3000 by 1000 and return 3s for 3 seconds elapsed.
If you need timestamps in seconds instead of milliseconds, change all instances of 1000 to 1 (which effectively multiplies everything by 1000 to go from milliseconds to seconds (ie: because 1000ms per 1s).
Here are the scaling units in more DRY form:
const SECOND = 1000
const MINUTE = SECOND * 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH = DAY * 30
const YEAR = MONTH * 12
We can also use console.time() and console.timeEnd() method for the same thing.
Syntax:
console.time(label);
console.timeEnd(label);
Label:
The name to give the new timer. This will identify the timer; use the same name when calling console.timeEnd() to stop the timer and get the time output to the console.
let promise = new Promise((resolve, reject) => setTimeout(resolve, 400, 'resolved'));
// Start Timer
console.time('x');
promise.then((result) => {
console.log(result);
// End Timer
console.timeEnd('x');
});
You can simply use performance.now()
Example:
start = performance.now();
elapsedTime = performance.now() - start;
var hours = 0;
if(minutes == 59 && seconds == 59)
{
hours = hours + 1;
minutes = '00';
seconds == '00';
}
I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.
I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be added.
(function(w){
var timeStart,
timeEnd,
started = false,
startTimer = function (){
this.timeStart = new Date();
this.started = true;
},
getPartial = function (end) {
if (!this.started)
return 0;
else {
if (end) this.started = false;
this.timeEnd = new Date();
return (this.timeEnd - this.timeStart) / 1000;
}
},
stopTime = function () {
if (!this.started)
return 0;
else {
return this.getPartial(true);
}
},
restartTimer = function(){
this.timeStart = new Date();
};
w.Timer = {
start : startTimer,
getPartial : getPartial,
stopTime : stopTime,
restart : restartTimer
};
})(this);
Start
Partial
Stop
Restart
What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):
var trace = console.log
function elapsed(op) {
this.op = op
this.t0 = Date.now()
}
elapsed.prototype.show = function() {
trace.apply(null, [this.op, 'msec', Date.now() - this.t0, ':'].concat(Array.from(arguments)))
}
to be used - for instance:
function debug_counters() {
const e = new elapsed('debug_counters')
const to_show = visibleProducts().length
e.show('to_show', to_show)
}

Categories