I have made a few countdown timers before but need to make a slight twist to this one. I need to make it countdown to Wednesday every week. So when it does reach Wednesday, it then renews and looks at going to next Wednesday, 7 days in the future.
So far I have used a very simple code block that takes up some space I'm afraid:
var td = new Date("Sep 16, 2015").getTime();
var days, hrs, mins, secs;
function recalc() {
var curdate = new Date().getTime();
var secsleft = (td - curdate) / 1000;
days = parseInt(secsleft / 86400);
secsleft = secsleft % 86400;
hrs = parseInt(secsleft / 3600);
secsleft = secsleft % 3600;
mins = parseInt(secsleft / 60);
secs = parseInt(secsleft % 60);
}
setInterval(function() {
recalc();
while(days<1 && hrs<1 && mins<1 && secs<1) {td.setDate(td.getDate() + parseInt(7)); recalc();}
$("#countdown").html(days + " Days " + hrs + " Hours " + mins + " Mins " + secs + " Secs");
}, 1000);
My problem is the last line of code. I am checking to see if it has all reached 0 or below. In my current case, several figures are in the negatives and the line does not trigger. Despite this, I am also receiving an error stating that td.getDate() is not a function.
EDIT: I am fairly certain my only remaining issue is why td.setDate(td.getDate() + parseInt(7)); is returning an error of: td.getDate() is not a function.
Everything is triggering correctly, all that is required is to add 7 days onto the td (target_date) and then it should rerun the recalc() function.
This won't work:
if(days<1 && hrs<1 && mins<1 && secs<1) {td.setDate(td.getDate() + 7);}
Because logically the cannot ALL be less than one at the same time. Once they all hit zero, the day switches to the next day. The last second of the day is actually 23:59:59.
You should go with:
if(days=0 && hrs=0 && mins=0 && secs<2) {td.setDate(td.getDate() + 7);}
I think that should help with part of it.
Related
I am trying two create to separate timers. One timer counts down to a date and displays a countdown and the other counts down on an interval and resets (ie: 5 hours and resets).
The one I am having trouble with is the second option. I am trying to create a countdown that is relative to real-time and then resets once it reaches zero. So for example setting it to 2 days and 5 hours. Once this completes the clock resets to 2 days 5 hours. I am having trouble getting the clock to reset at the specified time and loop without having negative numbers. I tried this two separate ways but feel like I am over-complicating things.
The reason I use real-time is so that the clock will be the same if you open it in another tab. If I create a regular timer it will reset upon refreshing the page.
codpen
In this example I tried to reset the counter every 40 seconds but couldn't get it to work. Ultimately I want to be able to specify the date with ie: 00:12:00 (12 hours countdown) and then have it reset automatically. I just can't figure out how to maintain the counting without going to negative numbers or freezing it.
function timer() {
var currentTime = new Date()
var date = currentTime.getDate()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var daysLeft = 0;
var hoursLeft = 24 - hours;
var minsLeft = 60 - minutes;
var secsLeft = 60 - seconds;
// counter freezes at 40 seconds and hangs for 20seconds
if(secsLeft => 40) {
secsLeft = 40 - seconds
if(secsLeft < 0) {
secsLeft = 40
}
}
document.getElementById('timerUpFront').innerHTML= "<br><br><strong>Duration Countdown with Infinite Reset #2</strong><br>" + daysLeft + " days " + hoursLeft + " hours " + minsLeft + " minutes " + secsLeft + " seconds";
}
var countdownTimer = setInterval('timer()', 1000);
codpen
you can separate the timer to functions to simplify it and apply the following logic
function startTimer () {
val targetRemainedSeconds = // calculate the value
val remainedSeconds = targetRemainedSeconds
setInterval(timer(), 1000)
}
function timer () {
remainedSeconds--
if (remainedSeconds < 0) reaminedSeconds = targetReaminedSeconds // reset the timer
timerUpdate()
}
function timerUpdate() {
// use 'remainedSeconds' to update timer
}
I need a simple countdown timer, but it is really bugging me that I can't seem to get it for some reason, and I think it's because of the special way I need it done, it has to adhere to these rules:
Must be every hour
Must be on the 30 minute mark
Must use UTC time
So for instance, it is 07:22 UTC, it would be 8 minutes till the next one.
If it were say, 07:30, it would say 1 hour till the next one.
And last but not least, if it were 07:31, it would say 59 minutes till the next one.
I was able to do this very easily for other countdowns I made, but those were for on the hour type things, it wasn't this complicated... I'm just stumped big time, please help me.
EDIT
Added sample code
var d = new Date();
var hoursUntil = 2 - d.getUTCHours() % 3;
var minutesUntil = 60 - d.getUTCMinutes();
var timestr = "";
if (minutesUntil === 60) {
hoursUntil++;
minutesUntil = 0;
}
if (hoursUntil > 0) {
timestr += hoursUntil + " hour" + (hoursUntil > 1 ? "s" : "");
}
if (hoursUntil >= 1 && minutesUntil > 1) {
timestr += " and " + minutesUntil + " minute" + (minutesUntil > 1 ? "s" : "");
}
if (minutesUntil > 1 && hoursUntil < 1) {
timestr += minutesUntil + " minute" + (minutesUntil > 0 && minutesUntil < 2 ? "" : "s");
}
bot.sendMessage(msg, "Next event will be in " + timestr + ".");
Let's do some thoughts. What we want to know is, when the minute hand next time shows 30. If we wanted to know only every half hour, we could just take the rest of division by 30 as you did with d.getUTCHours() % 3.
However, we want to get every 60 minutes, so we have do do somethingInMinutes % 60. The mark must be on shift from 60 to 0, so just add 30 minutes.
To have seconds precision, calculate that into seconds, add the current seconds and subtract both from 60 minutes (3600 seconds).
We want a timer that triggers on every second shift. Calculate the difference of 1000 and milliseconds.
<div>Seconds remaining until next 30 minutes mark: <span id="min-total"></span></div>
<div>minutes:seconds remaining: <span id="min-part"></span>:<span id="sec-part"></span></div>
<script>
var byId = document.getElementById.bind(document);
function updateTime()
{
var
time = new Date(),
// take 1800 seconds (30 minutes) and substract the remaining minutes and seconds
// 30 minutes mark is rest of (+30 divided by 60); *60 in seconds; substract both, mins & secs
secsRemaining = 3600 - (time.getUTCMinutes()+30)%60 * 60 - time.getUTCSeconds(),
// integer division
mins = Math.floor(secsRemaining / 60),
secs = secsRemaining % 60
;
byId('min-total').textContent = secsRemaining;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
// let's be sophisticated and get a fresh time object
// to calculate the next seconds shift of the clock
setTimeout( updateTime, 1000 - (new Date()).getUTCMilliseconds() );
}
updateTime();
</script>
Maybe I am missing something but as far as I can see, UTC and in fact hours in general are not relevant to this. It should be as simple as just calculating where the current minute is.
Maybe something like
now = new Date();
minutes = now.getMinutes();
if(minutes > 30) {
minutes_until = (60 - minutes) + 30;
}
else {
minutes_until = 30 - minutes;
}
I need for a clock to count from a specific time. e.g. Time is 20:08:00 and then to count from there. I have searched high and low for an answer and no one has specifically come up with an answer(that Ive seen). So my normal clock is like this.
<script type="text/javascript">
function clock()
{
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
if (minutes <= 9) minutes = "0" + minutes;
if (seconds <= 9) seconds = "0" + seconds;
dispTime = hours + ":" + minutes + ":" + seconds;
var basicclock = document.getElementById('basicclock');
basicclock.innerHTML = dispTime;
setTimeout("clock()", 1000);
}
clock();
</script>
So all I need is the time to start at say 20:08:00 (or a variable of time). I am wondering if it better to use a timer to achieve a set time and to count from that???
Any help would be appreciated.
First: Please try to extensively search SO for answers before asking questions, many helpful responses can be found if you look. ;)
If you are trying to countdown to a certain time/date I would recommend the answer found HERE
All code credit goes to author's answer above.
HTML - for display
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
Script (keep formatting and just modify the 4th line down for your target date)
setInterval(function(){
// set whatever future date / time you want here, together with
// your timezone setting...
var future = new Date("Sep 20 2014 21:15:00 GMT+0200");
var now = new Date();
var difference = Math.floor((future - now) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
$("#seconds").text(seconds + "s");
$("#minutes").text(minutes + "m");
$("#hours").text(hours + "h");
$("#days").text(days + "d");
}, 1000);
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
DEMO OF THE ABOVE CODE
I would also look at these are other interesting solutions found on this post here HERE
Im using this jquery plugin for time count down in my web app. Please help me out to remain the count down time not beginning at first each time.I want to set the cont down for a month (30 days 24h 60min 60 sec).So every time i refresh count down should not be started from the beginning.Thnx
here is the script code to set the time
$('#counter').countdown({
timestamp : (new Date()).getTime() + 30*24*60*60*1000
});
Does everyone need the same end time? For example, if you want to launch your site on March 5, 2014 at 5 PM Eastern, then you want to set the launch time like so:
var ts = new Date(Date.UTC(2014, 2, 7, 22))
$('#counter').countdown({
timestamp : ts
});
Alternatively, if each user needs to see a unique countdown, then you want to persist the time in a cookie. For example, if I open the page 5 minutes after you open the page. Should the timer be 5 minutes apart? If yes, then use the cookie. If no and both of our timers should be the same, then pass to the counter the desired end date.
Note: UTC is set if timezones matter for you.
var today = new Date()
var enddate = new Date(2014,05,01)
function calcDate(date1,date2) {
var datadiff = Math.abs(date1 - date2) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(datadiff / 86400);
datadiff -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(datadiff / 3600) % 24;
datadiff -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(datadiff / 60) % 60;
datadiff -= minutes * 60;
// what's left is seconds
var seconds = Math.floor(datadiff % 60);
var message = " ";
message += days + " days " ;
message += hours + " hours ";
message += minutes + " minutes \n";
message += seconds + " seconds \n";
return message
}
a = calcDate(enddate,today);
alert(a);
If you need persistence, rather than creating a new date object in javascript, pass the date from the backend which should be saved the first time you start the countdown.
There are many ways to persist data. One way might to to store the date into a cookie.
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
date = getCookie('date');
if(!date) {
document.cookie="date=" + new Date().getTime() + 30*24*60*60*1000 + ";";
date = getCookie('date');
}
alert(date);
That should help you persist the date between browser refreshes, but only as long as the cookie lasts.
Let me first say I do not have a deep understanding of javascript but I know how to work my way around enough to write small scripts for pages. A client of mine needs me to do the following for a website:
Find the user's local time on their computer.
Take that local time and subtract it from 6pm.
Display that time in a countdown or just a statement letting the user know how much time is left for same day shipping.
After 6pm the time resets or disappears until the next business day.
So far I've been able to create the logic for getting the time from the local computer. I thought I'd be able to use datejs but it does not calculate hours in a day.
Here is the current code I have:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
How about this:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (minutes < 10)
minutes = "0" + minutes
if (suffix == "PM" && hours >= 6)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 5 - hours;
var minsLeft = 60 - minutes;
document.write("<b> You've got " + hoursLeft + " hours and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
if this site would let me comment on other people's answers I'd give the credit for this to Giovanni, but since I can't yet comment on other people's work, here's what needs to change.
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (minutes < 10)
minutes = "0" + minutes
if (hours >= 18)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 17 - hours;
var minsLeft = 60 - minutes;
if(minsLeft==60){
minsLeft=0;
hoursLeft++;
}
document.write("<b> You've got " + hoursLeft + " and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
The reason for this is that people who are ordering at 5AM might see think that they have to submit within the next hour for their shipping to be next day when in fact they have the next 13 hours.
EDIT: saw your timezone concern and here is a post that might interest you.
EDIT 2: posted the wrong link. The correct one should be up now, though it might be a bit of a dated answer.
Something similar I solved also yesterday, so this is easy. Here is the javascript code:
function start_onload(last_hour){
var timeout_message = document.getElementById('timeout_message');
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var expire_time = 0; // in seconds
if (hours<last_hour) {
expire_time += (last_hour-hours-1)*3600;
expire_time += (59-minutes)*60;
expire_time += (59-seconds);
}
else {
timeout_message.innerHTML = 'It\'s after '+last_hour+' o\'clock!';
return;
}
var expire_time = currentTime.getTime() + 1000*expire_time;
//console.log(expire_time, hours, minutes, seconds, expire_time);
function countdown_session_timeout() {
var current_time = new Date().getTime();
var remaining = Math.floor((expire_time - current_time)/1000);
if (remaining>0) {
hours = Math.floor(remaining/3600);
minutes = Math.floor((remaining - hours*3600)/60);
seconds = remaining%60;
timeout_message.innerHTML = 'Countdown will stop in '+ hours + ' hours ' + minutes + ' min. ' + seconds + ' sec.';
setTimeout(countdown_session_timeout, 1000);
} else {
timeout_message.innerHTML = 'Time is up!';
}
}
countdown_session_timeout();
}
Full script # pastebin.com is here.
This is a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. After reaching 0 it automatically reset the counter. It goes again to 30 second and this process is continued in a loop
window.onload = function() { startCountDown(30,
1000, myFunction); }
function startCountDown(i, p, f) { var pause = p; var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
//fn();
startCountDown(30, 1000, myFunction); //stop
return; } setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
); } //set it going countDownObj.count(i); }
function myFunction(){};
</script>