Recurring function to reset variable/counter at midnight (moment.js, node.js) - javascript

I want to reset a variable during midnight. Every night.
I'm trying to build this function with Moment.js for Node but I can't seem to get the recurring part to work properly.
This is what I got so far.
// Calculate time to midnight
function timeToMidnight(){
var midnight = new Date();
midnight.setHours(0,0,0,0);
var now = new Date();
var msToMidnight = midnight - now;
console.log(' it is ' + msToMidnight + 'ms until midnight');
return msToMidnight;
};
// Reset counter at midnight
setTimeout(function(){
console.log("midnight, do something");
}, timeToMidnight());
How can I best make it recurring at midnight, every night?
Thanks in advance.

If you're using moment, consider instead this implementation
var moment = require('moment');
function timeToMidnight() {
var now = new Date();
var end = moment().endOf("day");
return end - now + 1000;
}
Like your function, this takes now milliseconds and calculates the number of milliseconds until midnight, but this is supported directly when using moment, which is nice. Add 1 extra second (1000 milliseconds) to get to the next day.
A typical pattern is for a function to call itself after a timeout.
function roundMidnight() {
console.log('at midnight');
setTimeout(roundMidnight,timeToMidnight());
}
setTimeout(roundMidnight,timeToMidnight());
Pretty generic, in fact depending on the value returned, you could schedule anything anytime, pretty useful, seem like someone must have thought of that.
node-schedule
A cron-like and not-cron-like job scheduler for Node.
And they did. Maybe what you really want is node-schedule. It looks like it's not really actively developed now, though.

Related

Create date object that is same for everyone from same timestamp

On my site I am getting the current time via ajax function that returns the servers current timestamp and then creating a date object.
$.post(flipCountdownObj.ajax_url, data, function(response) {
var currentTime = new Date(parseInt(response) * 1000);
alert("Server says the time is " + currentTime.toLocaleTimeString());
// code to create my countdown here...
}
My logic then goes on to compare that date to various other dates to provide countdowns and event status.
My problem is though that everyone is getting different times.
I am in GMT. The server is in EST. For me it says the correct time but people in EST are saying that it is 4 hours out.
I don't understand why this is happening as the timestamp should be the same for everyone.
I saw a post saying about setting UTC time but not sure exactly what I am meant to do. Can anyone shed some light on what I am doing wrong?
This seems to work:
var serverOffset = -300*60000; // -5 hrs is 300 minutes
var usersDate = new Date();
var userOffset = usersDate.getTimezoneOffset()* 60000;
var currentTime = new Date((parseInt(response) * 1000) + userOffset + serverOffset);

jquery library know when new day is coming

I wonder how can detect or know when new day is coming by using jquery or others jquery library.
For examples:
Assume, right now is 2016/06/23 23:59:50. And when second come to 2016/06/24 00:00:00, jquery can detect an event.
I know we can use setTimeOut or setInterval and check every seconds when new day is coming.
But i don't want to use these methods above, what methods of jquery do we detect ?
There's no automatic event that's triggered when the date changes. What you can do is calculate the time until the date changes, and use setTimeout to run a function when that happens.
var now = new Date;
var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
setTimeout(function() {
alert("It's tomorrow!");
}, midnight.getTime() - now.getTime());
The arguments to new Date() are the components of the date and time. Leaving out the time arguments defaults them all to 0. So adding 1 to the date and omitting the time will return the time of the next midnight.
You could write a little JavaScript class that continuously samples the time and fires an event when it happens. You listed jQuery, so let's use that to handle the events.
First, let's make the class which samples the time:
function DayChecker() {
var self = this;
// Get a copy of now to compare against
self.lastDate = new Date();
// A function that compares now to the lastDate, and fires the event
// if different, and resets the lastDate
self.sample = function() {
var tempDate = new Date();
// Compare the day component of the last sampled time to the
// current time
if (self.lastDate.getDay() != tempDate.getDay()) {
// It changed, so fire the event!
$(self).triggerHandler('daychange');
};
// Update the last sampled date so this can run forever and
// trigger on every day change
self.lastDate = tempDate;
}
// for illustration, a function that force changes the last date
// to trigger the event
self.forceChange = function() {
// Add 1 day to the last sample time to trip the event
self.lastDate.setTime(self.lastDate.getTime() + (1 * 86400000));
};
// Now start sampling every second (or whatever accuracy you need)
setInterval(self.sample, 1000);
};
Now we create a new instance of this helper class:
var dayChecker = new DayChecker();
And listen for the event I called "daychange":
$(dayChecker).on('daychange', function() {
alert('new day!');
});
And finally, run the function that changes the date for testing purposes after a few seconds:
setTimeout(function() {
// Testing only!
dayChecker.forceChange();
}, 5000);
You should see the alert after five seconds.
A jsFiddle

javascript - time counter since start date and time

I have a new business, where I just hired someone to work for me, I am trying to make it easy for her to track her time, so I created a clock in button, that creates a record in a database, I have it pop up a small window, that she can click to clockout when she is done working.
I want it to show her on that popup window a counter that will show how long she has been working, so I want to create a javascript or jQuery that will start at a certain time and count from there. She is on the East Coast, our company is in the Central Timezone, so 1 hour behind her.
How can I get a javascript to start from a certain time and keep updating the timer, so she can see something like this:
[You've been working for: 01:01:01 HH::MM::SS] - and it is actively updating, climbing up.
All the timers I've found are not about time itself, but about starting at a time and counting down, or starting at 0 and counting up.
Is there a way to tell it a start time, so that way if she reloads the page, it does not start from 0, but will start at the time she clocked in, then add the time since and start from there?
I know it can be done, but I'm more of a Perl guy than a Javascript guy. I'm doing this on Wordpress, so I could use PHP and just tell her to refresh the page to see the current amount of time and then have it on page load show the current amount of time, but I think having a counter would be better and make it easier for her.
is there some code already done that I could modify myself to make it work? I cannot find any, anywhere. I'm willing to do all the work, I'm not asking for someone to do it for me.
I found this example someone did:
function get_uptime() {
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
seconds = dif / 1000;
Seconds_Between_Dates = Math.abs(seconds);
document.getElementById("seconds").innerHTML = Seconds_Between_Dates;
setTimeout(get_uptime, 1000);
}
get_uptime();
That is sort of it, but I don't now how to put the first time in t1, what format do I put it in?
I can have PHP put it in any format, but not sure the one it needs.
Plus this appears to only put the seconds, not hours, minutes and seconds.
Is there away to do that?
Thanks,
Richard
From your question I understand you store the date and time on start?
So then you can use PHP to echo this information in a starting Date object and let a setInterval-function do the current timegetting and calculation of the time working.
See working example here: http://jsfiddle.net/c0rxkhyz/1/
This is the code:
var startDateTime = new Date(2014,0,1,23,59,59,0); // YYYY (M-1) D H m s ms (start time and date from DB)
var startStamp = startDateTime.getTime();
var newDate = new Date();
var newStamp = newDate.getTime();
var timer; // for storing the interval (to stop or pause later if needed)
function updateClock() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000);
var d = Math.floor(diff/(24*60*60)); /* though I hope she won't be working for consecutive days :) */
diff = diff-(d*24*60*60);
var h = Math.floor(diff/(60*60));
diff = diff-(h*60*60);
var m = Math.floor(diff/(60));
diff = diff-(m*60);
var s = diff;
document.getElementById("time-elapsed").innerHTML = d+" day(s), "+h+" hour(s), "+m+" minute(s), "+s+" second(s) working";
}
timer = setInterval(updateClock, 1000);
<div id="time-elapsed"></div>
Attention! The month number in the new Date() declaration is minus one (so January is 0, Feb 1, etc)!
I would use momentJS fromNow function.
You can get the time started as variable on page load then call fromNow on that and current time to get time between the two every time the clock is clicked:
var StartedWorkDateTime = GetStartedTime();
moment(StartedWorkDateTime).fromNow(true);
Non momentJS:
var date1 = new Date("7/11/2010 15:00");
var date2 = new Date("7/11/2010 18:00");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffHours = Math.ceil(timeDiff / (1000 * 3600));
alert(diffHours);
reference
Get the difference between two dates by subtracting them:
var duration = end - start;
This will give you the number of milliseconds between the dates. You can use the milliseconds to figure out hours, minutes, and seconds. Then it's just a matter of string manipulation and writing the value to the page. To update the timer once per second, use setInterval():
setInterval(writeDuration, 1000);

Create a scheduled Greasemonkey script

I need to create a special kind of script.
I want to show a message at certain times of the day. I've tested the code in Firebug Console and it works. The code is:
//Getting the hour minute and seconds of current time
var nowHours = new Date().getHours() + '';
var nowMinutes = new Date().getMinutes() + '';
var nowSeconds = new Date().getSeconds() + '';
var this_event = nowHours + nowMinutes + nowSeconds;
//172735 = 4PM 25 Minutes 30 Seconds. Just checked if now is the time
if (this_event == "162530") {
window.alert("Its Time!");
}
I feel that the Script is not running every second. For this to work effectively, the script has to be able to check the hour minutes and second "Every Second". I'm not worried about the performance, I just have to be accurate about the timing (to the second).
How do I do this?
Of course the script isn't running each second, GM-scripts run once when the document has been loaded.
Calculate the difference between the current time and the target-time and use a timeout based on the difference:
var now=new Date(),
then=new Date(),
diff;
then.setHours(16);
then.setMinutes(15);
then.setSeconds(30);
diff=then.getTime()-now.getTime();
//when time already has been reached
if(diff<=0){
window.alert('you\'re late');
}
//start a timer
else{
window.setTimeout(function(){window.alert('it\'s time');},diff);
}
Javascript doesn't guarantee your timeouts and other such events fire exactly on-time.
You should compare two Date objects using >= and remove the timeout or what ever other method you're using for tracking the time inside the matching if (and then reset it if necessary).
For more details see: https://stackoverflow.com/a/19252674/1470607
Alternatively you can use string comparison (but with caveats): https://stackoverflow.com/a/6212411/1470607

Do something at a specific time of the day js

How can i fire a function at a specific time and date. eg: 8:30 every Wednesday. The solution that i can think of is checking time with an interval but loops are laggy especially when you have to check every minute. Are there any alternative solution. Please help, thanks.
Something like...
var dateItHappens = new Date()
// ... set the dateItHappens variable up ...
var millisTillOccurence = dateItHappens.getTime() - new Date().getTime();
setTimeout(function(){ /* ... function you want to call ... */ }, millisTillOccurence);
if you are using node you can use node-cron package,
and
cron.schedule('* * * * * *',async()=>{
// your task
)
first star represent seconds, next minute and so on........

Categories

Resources