setInterval for longer hours - javascript

Is setInterval method reliable for longer hours?
I have a requirement to trigger functions for once everyday and/or once everyweek.
So am using setInterval(myFunc, 86400000) //For one day. similarly calculated number of milliseconds for one week
Is this a good approach. or is there anyother technique i can use.

I think a good option would be,
when the web page opens first store the date to local storage,
when its open normally check the date in local storage every minute
and then validate it and take action.
setIterval sounds like a very bad way of doing it here...
On start up get the data,
save the date using localStorage.setItem("date", datevariblename);
on load or everytime you in the set interval use
localStorage.getItem("date") to get the date value
Then do what every comparsion is required between current date and save date

setTimeout is pretty darn precise for longer periods. I had the requirement myself some time ago, so I did some testing across browsers. Even if you have a timeout that lasts 24 hours for instance, the callback gets fired precisely (variance is in the area of miliseconds).
setTimeout (or more exactly, the implementation) does not use a "countdown". It will ask the operating system to give it a SIGnal when the time period is over.

Related

return difference between now and a given date with conditions

I'm trying a very simple idea but hard to implement one.
I want to return the difference between two given dates and times in seconds. Note I want to get the same result in these conditions:
No matter if we test it in Chrome or Firefox. it should return the same result in both.
No matter if the end-user sets the Time Zone in his/her system in different time zones.
So I tried this:
// input your custom Date below
const date = new Date('2020-6-24 14:22:00'); // Set End Time
const dif = (date.getTime() / 1000) - ((new Date().getTime())/1000);
console.log(dif);
if you check this with different browsers with different timezones set in your system you will get different results!
I want all users (Those who set the timezone to Havana and Those who set the time zone to Tehran on their systems) see the same result.
The same result is the only thing I can think of right now.
The wired and confusing thing here is that if I log this simple log, I have different results in Firefox and Chrome:
console.log(new Date());
Note: I set my system's timezone to Havana.
There can definitely be many issues with handling dates and times, including time zones, leap years, leap seconds, and daylight savings time.
However that doesn't seem to be what's happening here. Remember that internally JavaScript Date objects use universal time (UTC), so once you have the time stored correctly, comparisons should work regardless of the time zones.
I used this function:
const dateDiffSeconds = function(date1, date2) {
return Math.round(Math.abs(date1.getTime()-date2.getTime())/1000);
}
Note that I'm using Math.round() to round up as well as Math.abs so it doesn't matter which date is larger. Notably, you can even subtract dates directly without getTime().
When I ran it in Firefox, Chrome and Node using various tests I got consistent results, including when I changed time zones.
One test to run is this: instead of using the current time, compare two preselected constant dates.
I suspect you're having trouble with one or both of these things:
Time zone representation: Specify the date in UTC time. If you want a user in Tehran to see the same time difference as in Havana, you have to make sure you send them both the same date. If the date is sent without the time zone specified, both clients will convert the date into local time, which means they'll be separated by time zones. Instead, send the dates in UTC time.
Browser synchronization: It's possible also that when you're testing the results in two different browsers, you're not keeping them synchronized tightly enough. When I tested it, I used setInterval() with a low timeout setting (much lower than a second) to keep comparing the current time with the test date. If you're just refreshing the browsers manually the times likely won't be the same.
It's probably easier to use Date.now() instead of new Date(). This returns a number of milliseconds that you can easily subtract.
Just don't forget that time measurement on computers is weird. You can end up with end - start < 0 for a variety of reasons.

Managing timezone & DST issue for javascript application

I am trying to create a scheduling application. The front end\UI is developed using JavaScript. The back end is a ASP.NET Web Api application which uses MSSQL server as the database. From the UI, user will schedule a job which can run daily/weekly/monthly. Each job can run for maximum of 3 months. The job will run on the server side at the specified time.
Assume user come and selects a job which will run for a week (From 23-Nov to 29-Nov) at 10 AM local time. In this case, I will make seven entries in the database starting from 23 nov (One for each day). Each row will have Start time, Start Date and some status related columns.
I have following querstions:
How do I store time information (10 AM in this case)on SQL server?
Should I get the time using JavaScript on client machine and then convert the same to UTC?
Should I get the time using JavaScript and also save the user time zone information?
What happens when DST related changes take effect?
Will library like momemnt.js will help in this scenario?
I am thinking of saving user timezone information and the saving his local time on the server.
Warning - Scheduling properly is hard. There's a lot more to consider. Please read this and this. Most of your questions are addressed there (though from the perspective of other languages, the challenges are the same).
You might also take a look at Quartz.net, which is sufficient for many scenarios.
To answer your specific questions:
How do I store time information (10 AM in this case) on SQL server?
For the recurrence rule, store the local time of the event. SQL Server has a time type, which works well for storing the time of day. You will need other fields for tracking the time zone, the start date, days of the week, and other pattern information.
For the specific instance that is scheduled to run, you calculate the UTC datetime based on all the information in the recurrence rule. At minimum, you schedule the next occurrence, and recalculate after each run. In some cases, you may decide to project the next N occurrences, depending on what you need to show to the users. (You could also use a datetimeoffset for this purpose. See datetime vs datetimeoffset.)
Should I get the time using JavaScript on client machine and then convert the same to UTC?
Should I get the time using JavaScript and also save the user time zone information?
To answer both questions: For scheduling, you should not discard the original input, which will be in the local time zone of the event being scheduled. That may or may not match the time zone of the user. You will need to ask the user to select the time zone of the event.
What happens when DST related changes take effect?
That's up to you. You will need to test this thoroughly. In general, there is a period of local time that is skipped, and a period of local time that is repeated.
When it is skipped, you have to decide when to run the event. Options include: 1) before the skipped time, 2) after the skipped time, and 3) not at all. In most cases, the preferred option is to run after the skipped time, by advancing the local time by the DST bias (usually 1 hour). For example, a daily event scheduled to run at 2:30 every day in Pacific time would run at 3:30 on the day of the spring-forward transition.
When it is repeated, you have to decide when to run the event. Options include: 1) at the first occurrence, 2) at the second occurrence, and 3) at both occurrences. In most cases, the preferred option is to run at the first occurrence only. For example, a daily event scheduled to run at 1:30 every day in Pacific time would run at 1:30 PDT, and not at 1:30 PST.
Exceptions to this include dealing with businesses that are open late into the evening and choose to stay open for the repeated hour. For example, a bar, restaurant, or movie theater. It is highly dependent on the specific use case and the choices made by the specific business.
Will library like moment.js will help in this scenario?
Not from a scheduling perspective, no. It can help with parsing, formatting, and validating input though. You might also use moment-timezone to help with selecting the event's time zone. If you were running this with node.js on the back end, then perhaps there would be more benefit.
The biggest challenge is actually one you have not talked about, which is maintaining the time zone data on your server. In your C# code, I recommend using Noda Time for this, instead of TimeZoneInfo. You can then update the tzdb data yourself as needed. You also need to think about the workflow of rescheduling the UTC instants of each occurrence, in the case that a time zone has changed its offset or daylight saving time dates.

Accuracy of JavaScript time over a period of a few hours

I need to code myself a mini, locally running HTML5 + JavaScript app, which I will use as a timer to time a person performing squats.
The idea is simple: When I press A on the keyboard, it will store the current time with seconds and miliseconds into a local table as a repetition start. When I press B, it will store the current time as a repetition end.
What I'm not 100% sure about is how reliable the JavaScript timestamp really is. What is my best bet here? Here are a few ideas:
run it on the latest version of Chrome
disable the internet connection, so that the OS will not sync/change its current time
Is there anything else I should be careful about?
I don't need the time to be absolutely exact, only relatively; meaning that the last timestamp minus the first timestamp will yield the real time taken to perform the whole session. I don't care to know exactly at what time it started.
If you're retrieving the system time in Javascript with something like Date.now() in order to measure the time between two events, then that will be exactly as accurate as the system time is on the local computer. How exactly accurate that is will depend entirely upon the clock in the local system and whether there are any changes to the system time during the measurement period.
If there are no changes to the system time (such as a clock sync with an external source), then most system clocks are pretty darn accurate these days. Measuring an event that takes minutes would likely be accurate within a few milliseconds which is more accuracy than you can achieve by marking start and stop with just a keypress anyway since the precision on exactly when the key is pressed relative to the start and stop of the event is certainly not better than several hundred milliseconds.

Should I use getHours() or getUTCHours for my Javascript?

I want to get the time on the computer of the person who is accessing my website. Should I use getHours() or getUTCHours()?
Short answer is it depends. If you want the hours as it displays on a clock for their timezone you will want getHours() as it returns the hours in their local time. If you want the hours in Universal Time (no timezone adjustment) then use getUTCHours()
I would recommend getUTCHours - keeping everything in UTC removes a lot of headaches when it comes to working with dates and times.
getHours will return the time according to their timezone, getUTCHours will get their time converted to UTC. Would probably be easier to use getUTCHours so everyone is returning their time in the same timezone.
It depends what you're using it for. If you want to get the user's local time, use getHours(). If you want to get something like a time offset (say, "hours until the new CoD is released in the UK"), use getUTCHours() as an absolute reference point. Bear in mind, however, that if the user's clock is set wrong, getUTC*() functions will return times that aren't really UTC - all they do really is remove the getGMTOffset() amount for you.
It depends on what you want to do, but i'd agree with Andrew, if you use getUTC*** it becomes easier for you to handle dates and times

Javascript - How do I make getTime() uniform across all computers?

Right now I'm getting a different number on my Desktop than I am on my laptop.
getTime() uses the local time settings. The time settings can be changed in one of two places:
Your OS (such as windows) may manage time; double click it on the taskbar
Your OS relies on the system BIOS, it's one of the reasons that motherboards have a battery installed on the mobo (to keep time and settings in case of system failure), modifications to the time in your BIOS should be reflect in the OS, and consequently in JavaScript
An alternative is to make your own getTime function which pulls the time from one source, such as a server. If you want to minimize network calls, it might be worthwhile to pull this time once and at the same time make a call to getTime(). Then, at some other time, when it's needed, issue a getTime() again, subtract the difference and add it to the server time. Note: if time is important, I advise against this, since a user can easily alter their system clock
Otherwise, if your computers are on the same network, you can use a scheduler and a batch process to sync the times - it won't be perfect, but it'll be close enough
Rather than use the javascript getTime() method, you should rethink your usecase.
If you're looking to timestamp a form submission (e.g. for a comment or form post) you should have the server generate the timestamp when handling the POST
If you want to have a consistent time client-side, consider making an ajax call to a simple web application that returns a timestamp. You could easily write one yourself, or you could use Yahoo's time service
Sync the clocks.
The OS should have an option to use a network time service. There could still be a slight difference, but it should not be more than a second or two, which is good enough for most purposes. How close do you need them to be?
getTime() gets the system time of the computer. However, if you really need to sync, it's best to sync with a web server that you have. Cheers!
You can't, at least not with JavaScript alone. JavaScript uses the system information on the client machine to determine what the time is. Now, if they're in different time zones, you can use the UTC() function to get them in UTC basis (seconds from midnight, Jan 1, 1970), but it's most likely that they just aren't synchronized.
That could be for a variety of reasons. The most likely causes:
The clocks might not be set identically. One (or both) could be wrong.
The clocks could be using different time zones.

Categories

Resources