javascript countdown from d:h:m:s - javascript

I'm new in javascript.
My PHP script returns a value in this format
d:h:m:s
Now I would like to have a countdown which is able to countdown each second from this.
I modified a countdown. This works once a time, after the countdown "ticks" each second it returns NaN all the time. Any idea what I do wrong?
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
var days = Math.floor(timestamp / 86400);
console.log(time,timestamp);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - hours * 3600) / 60);
var seconds = timestamp - ((days * 86400) + (hours * 3600) + (minutes * 60))-1;
$(this).data("time",""+days+":"+hours+":"+minutes+":"+seconds);
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>

As far as I can see you have 2 problems here:
after the first execution you change the pattern of the text you display in the h1. First you have 02:03:05:59. Then you want to write 02 days 03:05:58 into the tag. Next time you parse it, you get the error because you split at : and that does not work anymore as you have days instead of : as the seperator for the first part.
When calculating the minutes, you should also substract the days and not just the hours.
When you wan to keep the dd:hh:mm:ss format, you could do it like this:
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).text().split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
timestamp -= timestamp > 0;
var days = Math.floor(timestamp / 86400);
console.log(days);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - days * 86400 - hours * 3600) / 60);
var seconds = timestamp - days * 86400 - hours * 3600 - minutes * 60;
if (days < 10) {
days = '0' + days;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>

Your snippet goes from dd:hh:mm:ss to dd days, hh hours. So second time around, your tag contains non-parsable text.
I have changed it to something more precise. Something even MORE precise would be to give a timestamp in milliseconds in the future instead of something with seconds since it will take several seconds to render the page. If you round on minutes from the server, it would likely be better.
var aDay = 24*60*60*1000, anHour = 60*60*1000, aMin = 60*1000, aSec = 1000;
$(document).ready(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var date = new Date();
date.setDate(date.getDate()+parseInt(time[0],10))
date.setHours(date.getHours()+parseInt(time[1],10),date.getMinutes()+parseInt(time[2],10),date.getSeconds()+parseInt(time[3],10),0)
$(this).data("when",date.getTime());
});
setInterval(function() {
$('.countdown').each(function() {
var diff = new Date(+$(this).data("when"))-new Date().getTime();
var seconds, minutes, hours, days, x = diff / 1000;
seconds = Math.floor(x%60); x=(x/60|0); minutes = x % 60; x= (x/60|0); hours = x % 24; x=(x/24|0); days = x;
$(this).text(
days + ' day' +(days==1?", ":"s, ") +
hours + ' hour' +(hours==1?", ":"s, ") +
minutes + ' minute'+(minutes==1?", ":"s, ") +
seconds + ' second'+(seconds==1?".":"s.")
);
});
}, 500);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown" data-time="02:03:05:59"></h1>

Related

How i can create alert when time runs out in this code

Please help me with the code . How i can create alert when time runs out in this code. i want to set alert on when time runs out .
function makeTimer() {
// var endTime = new Date("29 April 2018 9:56:00 GMT+01:00");
var endTime = new Date("29 April 2020 9:56:00 GMT+01:00");
endTime = (Date.parse(endTime) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") {
hours = "0" + hours;
}
if (minutes < "10") {
minutes = "0" + minutes;
}
if (seconds < "10") {
seconds = "0" + seconds;
}
$("#minutes").html(minutes + "<span>Minutes</span>");
$("#seconds").html(seconds + "<span>Seconds</span>");
}
setInterval(function() {
makeTimer();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minutes"></span> <span id="seconds"></span>
Just test
const pad = n => ("0" + n).slice(-2);
var endTime = new Date();
// uncomment below
// endTime.setMinutes(endTime.getMinutes() + 15);// 15 minutes
// remove next line, it is just to show how the count down works without waiting 15 minutes
endTime.setSeconds(endTime.getSeconds() + 10);// 10 seconds
endTime = (Date.parse(endTime) / 1000);
function makeTimer() {
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
$("#minutes").html(pad(minutes) + " <span>Minute" + (minutes === 1 ? "" : "s") + "</span>");
$("#seconds").html(pad(seconds) + " <span>Second" + (seconds === 1 ? "" : "s") + "</span>");
if (seconds === 0 && minutes === 0) {
console.log("Done")
clearInterval(tId);
}
}
const tId = setInterval(makeTimer, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minutes"></span> <span id="seconds"></span>
Inside the function,you can simply check the values of hours, minutes and seconds.As you already have it, you can simply put an if condition to check whether the hour is 0 and minute is 0 and second is 0. Then in that condition you can simply send an alert message.

Javascript Date starts with 1 hour

I'm trying to create a counter that shows how much time you've spent on the site and I use sessionStorage to access the Date object from multiple pages.
The problem is that the counter starts at 01:00:00 even though I initialized the Date with 00:00:00.
Here is my code:
function checkTime(){
if(document.getElementById("clock")[13] == ''){
var d = new Date('2010-06-11T00:00:00');
sessionStorage.setItem('time', d);
}
}
function updateTime(){
checkTime();
var nDate = new Date(sessionStorage.getItem('time'));
nDate.setSeconds(nDate.getSeconds() + 1);
sessionStorage.setItem('time', nDate);
var hours = (nDate.getHours()<10 ? "0" : "") + nDate.getHours();
var minutes = (nDate.getMinutes()<10 ? "0" : "") + nDate.getMinutes();
var seconds = (nDate.getSeconds()<10 ? "0" : "") + nDate.getSeconds();
var timeString = hours + ":" + minutes + ":" + seconds;
document.getElementById("clock").innerText = timeString;
}
setInterval(updateTime, 1000);
It starts at 01:00 due to your timezone (UTC +1 CET Central European Time, Stockholm).
Create your date in the following manner:
const utcDate = new Date(Date.UTC(2019, 5, 11, 0, 0, 0)); // second param is the month-index, it start at 0, so 5 means june
console.log(utcDate);
Why don't use the unix timestamp, is really more simple and timezone free.
When user enter on the website
var d = new Date().getTime();
sessionStorage.setItem('time', d);
then
function updateTime(){
var nDate = new Date().getTime();
var startDate = sessionStorage.getItem('time');
var duration = nDate-startDate;
var seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
var timeString = hours + ":" + minutes + ":" + seconds;
document.getElementById("clock").innerText = timeString;
}
setInterval(updateTime, 1000);

Updating document.title every second

<script>
window.setInterval(function(){ document.title = "site - " + msToTime();}, 1000);
function msToTime() {
var milliseconds = parseInt((remainingTime % 1000) / 100),
seconds = parseInt((remainingTime / 1000) % 60),
minutes = parseInt((remainingTime / (1000 * 60)) % 60),
hours = parseInt((remainingTime / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
</script>
remainingTime would bring however much seconds left in the timer (00:07:19.7). When I change document.title to alert(), it would successfully give alerts every second, but I want the tab title to update every second. How would I accomplish this?
Here you go! That's what you wanted? I edited your code adding the functionality of time, test it! changing every millisecond.
P.S - If i were you i would delete the milliseconds. Stays more clean without it
window.setInterval(function(){ document.title = "rumseytime - " + msToTime();}, 1000);
function msToTime() {
var remainingTime = new Date();
var milliseconds = remainingTime.getMilliseconds();
seconds = remainingTime.getSeconds();
minutes = remainingTime.getMinutes();
hours = remainingTime.getHours();
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

How can I prevent this daily countdown timer from resetting at midnight?

Key variables to keep in mind:
This is set to simulate 11:00 PM.
var bt = "23:00";
This is set to simulate 8:00 AM.
var wt = "08:00";
The desired functionality:
The countdown timer starts every morning at 8:00 AM.
It counts down until 11:00 PM, every night.
Then it stays at 00:00:00.
In the morning, at 8:00 AM, it repeats the count-down, again.
This should happen forever.
What is actually happening:
Everything is working fine, except it is starting a 24 hour countdown at midnight, until 8:00 AM.
I have tried debugging this, and I suspect the error lies in what is calculated as the distance variable, making the code think that it is comparing against the next day, but I am not sure how to remedy this.
Here is the Codepen.
and here is my JS code:
$(document).ready(function () {
var bt = "23:00"; // 11:00 PM
var wt = "08:00"; // 08:00 AM
var dateNow = moment().format('MMM D, YYYY');
placeHolderDate = dateNow + " " + bt;
var timeNow = moment().format('HH:mm');
var countDownDate = new Date(placeHolderDate).getTime();
var countDownHourMin = (wt.split(":"));
// Update the count down every 1 second
var x = setInterval(function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
if (hours < 0 || minutes < 0 || seconds < 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
var timeNow = moment().format('HH:mm');
//console.log('Time Now:' + timeNow);
//console.log('Wake Time:' + wt);
if (timeNow === wt) {
clearInterval(x);
restartCountdown();
}
//console.log(hours + ":" + minutes + ":" + seconds);
}, 1000);
function restartCountdown() {
//log("restartCountdown Started!");
var bt = "23:00"; // 11:00 PM
var wt = "08:00"; // 08:00 AM
var dN = (moment().add(moment.duration({d: 1})).format('MMM D, YYYY'));
console.log('dn ' + dN);
var placeHolderDate = dN + " " + bt;
var countDownDate = new Date(placeHolderDate).getTime();
var countDownHourMin = (wt.split(":"));
// Update the count down every 1 second
var x = setInterval(function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
if (hours < 0 || minutes < 0 || seconds < 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
// console.log(hours + ":" + minutes + ":" + seconds);
}, 1000);
}
});
I have edited your code and created this codepen https://codepen.io/anon/pen/aabjEb?editors=0010. Please feel free to optimize the code since I have not done it. The idea was is check if time is between 8 AM and 11 PM. If yes show value else show 00:00:00. Also once the date changes, update the dates and now compute accordingly
$(document).ready(function () {
function countdown() {
var bt = "23:00", // 11:00 PM
wt = "08:00"; // 08:00 AM
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth()+1,
yyyy = today.getFullYear();
var startTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + wt),
endTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + bt);
setInterval(function() {
var now = new Date();
var nowdd = today.getDate();
var nowTime = now.getTime();
if(dd !== nowdd) {
dd = nowdd;
var nowmm = now.getMonth() + 1,
nowyyyy = now.getFullYear();
startTime = new Date(dd + '/' + mm + '/' + yyyy + ' wt');
endTime = new Date(dd + '/' + mm + '/' + yyyy + ' bt');
}
if(nowTime > startTime && nowTime < endTime) {
// Find the distance between now and the count down date
var distance = endTime - nowTime;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
} else {
$("#countDown").val("00:00:00");
}
}, 1000);
}
countdown();
});

timestamp countdown going in negative

I have a script that countdowns timestamp. It is working fine but the problem it keeps going less than 0 into negative. I want it to stop at zero.
// $nowtime is a date in future
var startLive = new Date("<?php echo $nowtime; ?>");
var timestamp = startLive - Date.now();
timestamp /= 1000; // from ms to seconds
function component(x, v) {
return Math.floor(x / v);
}
var $div = $('.time');
timer = setInterval(function() {
timestamp--;
var days = component(timestamp, 24 * 60 * 60),
hours = component(timestamp, 60 * 60) % 24,
minutes = component(timestamp, 60) % 60,
seconds = component(timestamp, 1) % 60;
$div.html(days + " days, " + hours + ":" + minutes + ":" + seconds);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Output looks like 1 Days, 6:10:30
Problem is if it is less than zero it still goes in negative. something like -3 days, -3:-5:-5
How to stop at 0.
Thanks.
timer = setInterval(function() {
/* if timestamp <= 0 return means skip rest of function */
if(timestamp <= 0) {
clearInterval(timer);
return;
}
timestamp--;
var days = component(timestamp, 24 * 60 * 60),
hours = component(timestamp, 60 * 60) % 24,
minutes = component(timestamp, 60) % 60,
seconds = component(timestamp, 1) % 60;
$div.html(days + " days, " + hours + ":" + minutes + ":" + seconds);
}, 1000);
if(timestamp <= 0)
{
clearInterval(timer);
}

Categories

Resources