How to reinit timer when it end? - javascript

everyone! On a website I use this timer, but I do not understand what I need to do when it end. When timer are end it should restart for next 14 days.
You may advice some books, where I can read about my problem or just aboud Date() in js.
Thanks!

There is a callback option for this plugin that is called as soon as you timer ends:
$('#countdown').timeTo({
timeTo: new Date(new Date('Sat Apr 25 2015 09:00:00 GMT+0200')),
displayDays: 2,
theme: "black",
displayCaptions: true,
fontSize: 48,
captionSize: 14,
// important part
callback: function(){
alert('Timer ended');
}
});
When you want to keep track of an user's exprieing time localStorage-API can be used to accomplish this.
Start expiring Timer:
Make a function to keep track of user's expiring date by using localStorage.This function returns the start date when an user visited your site the very first time. This date is used to determine whether an user has already extended the expire time of 14 days but further details are listed below:
function handleUserDate(expireInDays){
var now = new Date();
var startDate = localStorage.getItem('timerStartDate');
// has user already visited your site?
if(startDate){
// is user'date expired?
startDate = new Date(Number(startDate));
var futureDate = new Date(startDate.getTime()+expireInDays*(1000*60*60*24));
if(now.getTime() < futureDate.getTime()){
console.log('in future');
return startDate;
}
}
console.log('in past');
localStorage.setItem('timerStartDate', now.getTime());
return now;
}
Next function is used to activate a timer and putting the number of days that are left into the timeTo option:
function startTimer(inDays){
var now = new Date();
var futureDate = new Date(now.getTime()+inDays*(1000*60*60*24));
console.log(futureDate);
$('#countdown').timeTo({
timeTo: futureDate,
displayDays: 2,
theme: "black",
displayCaptions: true,
fontSize: 48,
captionSize: 14,
callback: function(){
alert('Timer ended');
var daysInFuture = 14;
startTimer(daysInFuture);
}
});
}
A Function to calculate the time difference in days between start date and now:
function getTimeDiff(date, date2, diff){
return Math.abs(date.getTime()-date2.getTime())/diff;
}
Put it all together:
var expireinDays = 14;// 14 day max
var startDate = handleUserDate(expireinDays);
console.log(startDate);// returns date of the very first time or when already expired it returns current date
var now = new Date();
var dayInMill = 1000*60*60*24;
var dayDifference = getTimeDiff(startDate,now,dayInMill);
dayDifference = expireinDays - dayDifference;
console.log(dayDifference); // days left
startTimer(dayDifference); // show timer

Related

How to run function() frequently on specific times of the day in javascript

I have a function which runs every 3 minutes 24/7 using setTimeout(). The problem is that it fetches data from an API that have an maximum of request a month. I want to run it as often as a can but it´s unnecessary to do so when i am a sleep because of the waste of requests. How can in addition only run my script between for example 06:30:00 and 20:00:00?
You will need both setTimeout and Date() to achieve this :
for e.g.
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);
For more details please follow this
I have tested and verified following code. Mine is 7:22 PM which comes under these timings and it executes very well.
// get todays strict timings
// 06:30:00 and 20:00:00
setInterval(function() {
lowerDate = new Date();
lowerDate.setHours(6);
lowerDate.setMinutes(30);
lowerDate.setSeconds(0);
upperDate = new Date();
upperDate.setHours(20);
upperDate.setMinutes(0);
upperDate.setSeconds(0);
todayDate = new Date();
if (todayDate > lowerDate && todayDate < upperDate)
console.log("execute"); // execute only if in between these times
}, 3 * 60 * 1000) //Every 3 minutes

How to find if we passed a day when adding minutes to datetime object in javascript

I am having a date range from June 21 to Jun 27.I want to add 20 minutes to my start date every 5secs and make a service call to get some values. Also, for the second service call I need my previous end datetime as start datetime.For example for service call 1,
my start date is Jun 21, 5:00 PM
my end date is Jun 27, 5:20 PM
my second service call should have
start date as Jun 21, 5:20 PM
end date as Jun 21 , 5:40 PM
How can I achieve this through javascript and also how do I change date once I pass 24 hrs.
Thanks!
//My start date and end date
var startDt = newDate(data.startDate);
var endDt = newDate(data.endDate);
var count = 0;
setInterval(function()
{
if(count == 0){
var sDt= new Date(startDt).toISOString();
var eDt= new Date(startDt.setMinutes(startDt.getMinutes() + 10)).toISOString();
}
else{
var sDt = new Date(startDt.setMinutes(startDt.getMinutes() + )).toISOString();
}
//calling my apy with sDt and eDt here;
count++;
},5000)
The Javascript setMinutes() method will automatically go to the next hour or day when the minutes or hour wrap around.
startTime = new Date(endTime); // Copy old endTime to startTime
endTime.setMinutes(endTime.getMinutes() + 20); // add 20 minutes to endTime
Here's the full code:
//My start date and end date
var startDt = newDate(data.startDate);
var endDt = newDate(data.endDate);
var count = 0;
var interval = setInterval(function()
{
if (new Date() > endDt) { // Reached the endDt
clearInterval(interval);
return;
}
var sDt = new Date(startDt).toISOString();
var eDt = new Date(startDt.setMinutes(startDt.getMinutes() + 20)).toISOString();
//calling my apy with sDt and eDt here;
count++;
},5000)
if you want to run a function every five seconds
var dt = new Date(2016,6,21)
setTimeOut(function(){
//add 20 minutes to dt
dt = new Date(dt.getTime()+(20*60000)) // dt will be your start time
//end time is add 20 minutes to start time
var endDT = new Date(dt.getTime()+(20*60000));
//now call you ajax, return what ever you need along with dt and endDT
},5000//five seconds);
you could use momentjs to add seconds to your startDate like this
var startDate = moment('Jun 21, 5:00 PM');
startDate.add('20','minutes');
it will automatically maintain the coherence of the timestamps

How do I set Australia/Melbourne timezone to a countdown timer using momentjs

How do I add Australia/Melbourne timezone to the code below so regardless of the users location it displays the correct time. I have risul:moment-timezone installed however everything I do just breaks the countdown. Any help is appreciated.
Template.countdownTimer.onRendered(function() {
var today = new Date();
var sunday = new Date(today.getFullYear(),today.getMonth(),today.getDate()+(7-today.getDay()), 23, 59, 59);
$('#countdown').countdown(sunday, function(event) {
$(this).html(event.strftime('%d days %H hours %M minutes %S seconds'));
});
});
Update
var today = moment();
var sunday = new Date(today.getFullYear(),today.getMonth(),today.getDate()+(7-today.getDay()), 23, 59, 59);
console.log(sunday);
var clock = $('.clock').FlipClock(today, {
clockFace: 'DailyCounter',
countdown: true
});
I solved it reading the momentjs documentation then as below:
let time = moment(date).parseZone("Australia/Melbourne");
return time.format('YYYY:MM:DD HH:mm:ss:SSS');
This is how you can do for any country/Area for doing this you just have to know timezone
var timeZone = {hr:5, min:30} // for india
var utcOffset = parseInt(timeZone.hr) * 60 + parseInt(timeZone.min);
todayDate = moment().utcOffset(utcOffset);
Please user .format methods for trturning the value.
This will return the current time of any timezone.

Javascript asynchronous for loop

Is there a way for me run codes asynchronously in a for loop?
In this example, events from day x to y are required to be added into the calendar through a for loop. However the loop is taking roughly a min and its too long, as it is required to go through and add all the days from Jan 4, 2016 to Dec 28, 2020.
Right now, I will have to wait for all the days to be loaded to view the result.
Is there a way for events to get added and appear as soon as the 'addEventSource' is fired / before it goes through all the whole loop. Is it possible to make it asynchronous?
Javascript
$(document).ready(function () {
loadCalendar(null);
var start = new Date("Jan 4, 2016 08:00:00");
var end = new Date("Dec 28, 2020 12:00:00");
var startTime = new Date("Jan 4, 2016 08:00:00");
var endTime = new Date("Jan 4, 2016 12:00:00");
addCalendarEvents("Test", start, end, startTime, endTime);
});
function addCalendarEvents(title, start, end, repeatDays, startTime, endtime) {
var events = [];
var one_day = (24 * 60 * 60 * 1000);
var loopEnd = end.getTime();
for (var loop = start.getTime() ; loop <= loopEnd; loop = loop + one_day) {
var eventDate = new Date(loop);
var tempStart = start;
var tempEnd = end;
tempStart.setDate(eventDate.getDate());
tempStart.setMonth(eventDate.getMonth());
tempStart.setFullYear(eventDate.getFullYear());
tempEnd.setDate(eventDate.getDate());
tempEnd.setMonth(eventDate.getMonth());
tempEnd.setFullYear(eventDate.getFullYear());
$('#calendar').fullCalendar('addEventSource', [{
title: title,
start: tempStart,
end: tempEnd,
allDay: false
}]);
}
}
p.s. $('#calendar').fullCalendar('addEventSource', event) adds events to the calendar.
Javascript doesn't have a threading model, but it does have asynchronous timers.
Check this out: http://www.sitepoint.com/multi-threading-javascript/
As Tibrogargan mentioned, it can be achieved using setTimeout/setInterval.
The idea is to run the for loop for certain time and break the loop. again trigger the loop after certain time from where it has stopped earlier. This way you will not block the user.
eg..
var thresholdTime = 500;
function searchForData(searchTerm, indexFromWhereToSearch) {
var startTime = new Date(),
searchFrom = indexFromWhereToSearch;
for (var i=searchFrom; i < hugeData.length; i++) {
.......
if (newDate() - startTime >= thresholdTime) {
setTimeout((function(index) {
return function() {
searchForData(searchTerm, index);
}
})(i+1), 300/*another threshold*/);
break/return;
}
}
}

flipclock countdown to specific date in specific timezone without reset

I am trying to create countdown to a specific date using flipclock without the timer resetting or people in different time-zones seeing different numbers. For example, I want to countdown to Feb 20, 12:00am MST.
My problem is that the clock resets when the browser is refreshed after it reaches 0, the time shows negative numbers. If people viewing this clock with the current configuration, it is counting down to Feb 20, 12am in their timezone.
I've started with the countdown to New Years compiled clock and set my date, but not sure how else to address the timezone and reset issues.
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 0, 1, 20, 0, 0);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: false,
callbacks: {
stop: function() {
$('.message').html('The clock has stopped!');
}
}
});
});
var clock;
$(document).ready(function() {
// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
currentDate.setHours(currentDate.getHours() - 7);
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 0, 1, 20, 0, 0);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Limit time difference to zero
if (diff < 0) {
diff = 0;
}
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: false,
callbacks: {
stop: function() {
$('.message').html('The clock has stopped!');
}
}
});
});
Part solving timezone issue (a bit ugly):
// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
currentDate.setHours(currentDate.getHours() - 7);
Part limiting time difference to not less than zero:
// Limit time difference to zero
if (diff < 0) {
diff = 0;
}
Since the time you'd like to count down to is a specific time in a specific time zone, then the easiest way is to pre-convert that time to UTC, and count down to that instead.
On Feb 20th 2016, US Mountain Time is at UTC-7, therefore:
2016-02-20 00:00:00 MST == 2016-02-20 07:00:00 UTC
So,
var currentDate = new Date();
var futureDate = Date.UTC(currentDate.getUTCFullYear(), 1, 20, 7, 0, 0);
var diff = (futureDate - currentDate.getTime()) / 1000;
I'll let someone else answer WRT the specifics of FlipClock and your reset issue - though you might consider asking it in a separate question. (Try to ask only one question at a time in the future.)

Categories

Resources