24 hours countdown that restarts once page refreshes - javascript

i created this countdown that counts down 24 hours but once the page is refreshed,it restarts the countdown
how can i make it not start again?
please can anyone help me understand what i can do or to make it a static countdown
here are the codes
function getTimeRemaining(endtime) {
const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
return {
total,
days,
hours,
minutes,
seconds
};
}
function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const daysSpan = clock.querySelector('.days');
const hoursSpan = clock.querySelector('.hours');
const minutesSpan = clock.querySelector('.minutes');
const secondsSpan = clock.querySelector('.seconds');
function updateClock() {
const t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
const deadline = new Date(Date.parse(new Date()) + 1 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
<div>
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
</div>
i'd really appreciate any help regarding this
I dont know what way to go about it

To not restart the countdown once the page is refreshed, the deadline data needs to be saved into a persistent storage that does not get cleared out even when the page is refreshed. You can achieve this by storing the deadline data in localStorage.
localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed. - Source: LocalStorage
The change required on your code:
let deadline;
const prevDeadLine = localStorage.getItem("deadlineData"); // Get previous data from local storage
if (!prevDeadLine) {
deadline = new Date(Date.parse(new Date()) + 1 * 24 * 60 * 60 * 1000);
localStorage.setItem("deadlineData", deadline); // set the data for the first time
} else {
deadline = prevDeadLine; // use previousDeadline
}
Solution Snippet:
<html>
<head>
<title>
Countdown
</title>
</head>
<body>
<div>
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
</div>
</body>
<script>
function getTimeRemaining(endtime) {
const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
return {
total,
days,
hours,
minutes,
seconds
};
}
function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const daysSpan = clock.querySelector(".days");
const hoursSpan = clock.querySelector(".hours");
const minutesSpan = clock.querySelector(".minutes");
const secondsSpan = clock.querySelector(".seconds");
function updateClock() {
const t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ("0" + t.hours).slice(-2);
minutesSpan.innerHTML = ("0" + t.minutes).slice(-2);
secondsSpan.innerHTML = ("0" + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
} else {
new Date(Date.parse(new Date()) + 1 * 24 * 60 * 60 * 1000);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
let deadline;
const prevDeadLine = localStorage.getItem("deadlineData");
if (!prevDeadLine) {
deadline = new Date(Date.parse(new Date()) + 1 * 24 * 60 * 60 * 1000);
localStorage.setItem("deadlineData", deadline);
} else {
deadline = prevDeadLine;
}
initializeClock("clockdiv", deadline);
</script>
</html>

Related

Uncaught TypeError: Cannot read property '2' of null

I have JS timer that but my cookie script is giving this error:
Uncaught TypeError: Cannot read property '2' of null
The error appears only when reloading the page. So I assume the cookie is there but there is another problem I can't find. The error comes from this line: deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
Here is HTML
<div id="clockdiv">
I'm a timer
<span class="days hide"></span>
<span class="hours hide"></span>
<span class="minutes"></span> :
<span class="seconds"></span>
</div>
Here is JS
function getTimeRemaining(endtime) {
const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
return {
total,
days,
hours,
minutes,
seconds
};
}
function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const daysSpan = clock.querySelector('.days');
const hoursSpan = clock.querySelector('.hours');
const minutesSpan = clock.querySelector('.minutes');
const secondsSpan = clock.querySelector('.seconds');
function updateClock() {
const t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
//const timeInMinutes = 8;
//const currentTime = Date.parse(new Date());
let deadline;
// if there's a cookie with the name myClock, use that value as the deadline
if(document.cookie && document.cookie.match('myClock')){
// get deadline value from cookie
deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
} else {
// otherwise, set a deadline 10 minutes from now and
// save it in a cookie with that name
// create deadline 10 minutes from now
const timeInMinutes = 8;
const currentTime = Date.parse(new Date());
deadline = new Date(currentTime + timeInMinutes*60*1000);
// store deadline in cookie for future reference
document.cookie = 'myClock=' + deadline + '; path=/; domain=.codepen.io';
}
initializeClock('clockdiv', deadline);
Try to use ready-made Cookie functions, for ex., from here http://w3schools.com/js/js_cookies.asp
So
deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
could be replaced with
deadline = getCookie('myClock');
Have a look here http://jsfiddle.net/vyspiansky/po2zw4um

How to use this multiple times

I want to display this in several elements on the page. And it displays only once. In other elements it is empty. Do you have any solution regarding this issue?
Need to display it in a loop? Can you construct such a loop? As I created and wanted to display by class, no id unfortunately did not work.
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
function getNextSaturday() {
var now = new Date();
var nextSaturday = new Date();
nextSaturday.setDate(now.getDate() + (6 - 1 - now.getDay() + 7) % 7 + 1);
nextSaturday.setHours(11, 0, 0, 0);
return nextSaturday;
}
function convertToEST(date){
estOffset = -5.0
utc = date.getTime() + (date.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * estOffset));
}
var deadline = getNextSaturday();
initializeClock('clockdiv', convertToEST(deadline));
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>

Javascript JQuery countdown timer loop

Using the following JavaScript, how do I make it automatically restart the countdown adding 7 days when the deadline is reached?
(function($) {
"use strict";
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds,
};
}
function initializeClock(id, endtime) {
var daysSpan = $('.days');
var hoursSpan = $('.hours');
var minutesSpan = $('.minutes');
var secondsSpan = $('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.html(t.days);
hoursSpan.html(('0' + t.hours).slice(-2));
minutesSpan.html(('0' + t.minutes).slice(-2));
secondsSpan.html(('0' + t.seconds).slice(-2));
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date("Aug 24, 2018");
initializeClock('clockdiv', deadline);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
<span class="days"></span> Days
<span class="hours"></span> Hours
<span class="minutes"></span> Minutes
<span class="seconds"></span> Seconds
</div>
why dont you just re-initialize the script with a new deadline?
if (t.total <= 0) {
clearInterval(timeinterval);
var newDeadline = deadline.setDate(deadline.getDate() + 7);
initializeClock('clockdiv', newDeadline);
}

Unable to assign value to variable using "document.getElementById.value" [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 4 years ago.
I am trying to make a countdown timer in which the user can set day, hour, minute and seconds values.
The setlength() function takes the values from the textboxes then sets the variables.
Then when the user clicks the start button, the time in ms (variable lengthms) is calculated and added to the current time.
Then the countdown timer just counts down.
I am quite sure the counting down bit works but I don't understand/know why the script is unable to fetch the values from the input boxes and assign them to the variables.
Any help or another solution to varying the value of the hours minutes and seconds is appreciated.
Thank you in advance!
function setlength() {
var lengthd = document.getElementById("lengthd").value;
var lengthh = document.getElementById("lengthh").value;
var lengthm = document.getElementById("lengthm").value;
var lengths = document.getElementById("lengths").value;
}
function start() {
var lengthms = (lengthd * 24 * 3600 + lengthh * 3600 + lengthm * 60 + lengths * 1) * 1000;
var deadline = new Date(Date.parse(new Date()) + lengthms);
initializeClock('timerdiv', deadline);
}
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 500);
}
<!DOCTYPE html>
<html>
<body>
<h1>Countdown Timer</h1>
<div id="timerdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
<center>
<p id="length"></p>
Days: <input type="number" id="lengthd"> Hours: <input type="number" id="lengthh"> Minutes: <input type="number" id="lengthm"> Seconds: <input type="number" id="lengths"><br>
<button class="button set" onClick="setlength()">Set</button>
</center>
<center>
<div><button class="button start" onClick="start()">Start</button></div>
</center>
</body>
</html>
Your function setlength() declares all the lengths as local variables, so they are only usable from within that function.
Instead of
function setlength() {
var lengthd = document.getElementById("lengthd").value;
var lengthh = document.getElementById("lengthh").value;
var lengthm = document.getElementById("lengthm").value;
var lengths = document.getElementById("lengths").value;
}
you should declare the variables outside of your function
var lengthd;
var lengthh;
var lengthm;
var lengths;
function setlength() {
lengthd = document.getElementById("lengthd").value;
lengthh = document.getElementById("lengthh").value;
lengthm = document.getElementById("lengthm").value;
lengths = document.getElementById("lengths").value;
}
Note that I haven't checked the rest of your code, since you're sure that it works.

Date and include time to countdown using javascript

i am trying below code for countdown to on exact date and time. I mean, i wants to make a under contractions website countdown date (include exact time). but date are not count downing. js code just showed me wrong count and not downing second, min, hours, day. This js code has problem, but i don't understand, exactly where is the problem.
Here is code:
(function init() {
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date("03/13/2018 9:30 AM"));
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(endtime){
var timeinterval = setInterval(function(){
var t = getTimeRemaining(endtime);
document.querySelector(".days > .value").innerText=t.days;
document.querySelector(".hours > .value").innerText=t.hours;
document.querySelector(".minutes > .value").innerText=t.minutes;
document.querySelector(".seconds > .value").innerText=t.seconds;
if(t.total<=0){
clearInterval(timeinterval);
}
},1000);
}
initializeClock(((new Date()).getFullYear()+1) + "/1/1")
})();
I made some modifications to your code.
I added a displayTime() function that handles the time display.
initializeClock() now calls displayTime() directly when it's called, without waiting one second.
getTimeRemaining() now calculates the right time, by taking the current date into account, and not a random date: var t = Date.parse(endtime) - Date.parse(new Date());
function displayTime(date){
var t = getTimeRemaining(date);
document.querySelector(".days > .value").innerText = t.days;
document.querySelector(".hours > .value").innerText = t.hours;
document.querySelector(".minutes > .value").innerText = t.minutes;
document.querySelector(".seconds > .value").innerText = t.seconds;
return t;
}
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(endtime) {
displayTime(endtime);
var timeinterval = setInterval(function() {
t = displayTime(endtime);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}, 1000);
}
initializeClock("2018/03/13 09:30")
<div class="days"><span class="value"></span> days</div>
<div class="hours"><span class="value"></span> hours</div>
<div class="minutes"><span class="value"></span> minutes</div>
<div class="seconds"><span class="value"></span> seconds</div>
I think you are making this overly complicated. If you just start with a date and then every second, subtract one second from that start date, you're done.
var out = document.getElementById("output");
var start = new Date();
setInterval(function(){
start = new Date(start.getTime() - 1000);
out.textContent =
start.getHours() + " Hours, " + start.getMinutes() + " Minutes, " + start.getSeconds() + " Seconds";
},1000);
<div>Counting down from current time</div>
<span id="output"></span>

Categories