I need to get a uniform javascript time for all clients in our private server. So I want to set the javascript time of a client on initialization to the time of the server.
Right now I am thinking of setting a setInterval that will increment a variable that has a timestamp, but I think it would be too much to have a setInterval running in the back every n milisecond.
So is there a way for me to set the starting time of javascript? so every instance of new Date will be based on that, not the system time of the client?
A difference of 1-2 seconds from the server time is ok but if a difference of milliseconds is achievable then that would be better.
Any suggestions?
Have your server output it's current timestamp, and then calculate the difference between the client timestamp and server timestamp.
<script>
var serverEpoch = 1408602887; // written dynamically by the server
var epochDiff = Math.round(Date.now()/1000)-serverEpoch;
</script>
Now you have the difference between the server time and client time in seconds stored in epochDiff, which you can use for time calculations.
As I mentioned in my comment, this only works if your pages are generated constantly generated rather quickly. If the time can fluctuate (say between 5-2000ms), it would be a better idea getting the server time dynamically from a dedicated, fast script using XMLHttpRequest().
Related
It is not a duplicated question. If you doubt, read it to the end.
Problem: I am creating a web page that is shown in a SmartTV browser and I can't rely or trust this device's clock. The time is always wrong and there is no date registry.
Solution: I use ajax to get my location's current date and time from a time server API. It sends back year, month, week day, month day, hour and minutes. I don't care about the exactly seconds.
How to: What I don't know how to do is to get this information and turn it to a working clock that refreshes in the browser when time and day goes up. I fetch the time server every hour to ensure it still in sync, but between this hour, how can I make the JavaScript counts the minutes, hours, days, months and years correctly?
Option 1: use setInterval(). For example:
var numElapsedSeconds = 0;
setInterval(function() {
numElapsedSeconds++;
}, 1000);
Then add numElapsedSeconds to the last timestamp you received from the server and you have a (more or less) reliable current time.
Option 2: when you get an update from the server, also check the local clock, figure out the delta, and from that point on use the delta with the local clock to get the "real" time. Even if the local time settings are wrong, I'm assuming that time still progresses at the same speed as on the server (maybe unless the user tweaks it all of a sudden). Not sure what your use-case is but maybe this could be reliable enough...
You could also combine the two options for maximum accuracy (to compensate for the interval not being called exactly every 1000 milliseconds).
I want to run a scheduled job every 10 minutes which will do the following:
Check the table records and delete those who hasn't been updated for 10 minutes.
How is it possible to get the current server date in javascript in order to compare it?
Use the JavaScript Date object. Just creating a new Date object without parameters will give you the server date and time. It will of course be in GMT as all the servers in Azure run on GMT. However, be aware of clock drift. Each of the servers could be slightly off from one another time wise, so it may not be exact if comparing times across servers.
var cutOfDate = new Date();
You could also load up one of the JavaScript data libraries like Moment or something like that as well if you need to do a lot of date formatting or evaluations.
Another option is to simply have a stored procedure that is called to perform your clean up for you. The stored procedure could then use the SQL GETDATE() to determine the current date and do the deletes based on that.
I think what you want is this. Giving you an overview:
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-use-server-scripts/#access-tables
For date and time
http://azureinmycloud.net/2011/10/26/working-with-datetime-now-in-windows-azure-apps/
I have php file, that generates json with a countdown seconds to the New Year eve and to some birthdays. But I want the countdown to change every one second. Is it safe (will it overload the server) if I setTimeout(1000) to my ajax call function?
And what's the best way to implement 1 second JSON call via jQuery?
Thank you
Instead of overloading your server with requests (take into context you might have many users doing many requests at once coupled to your constants callbacks), take your data all at once for the following day for example and process the birthdays only in javascript.
The only Ajax portion i'd use in there would be to load more birthdays once per hour or day in case you have a really hyped user that leave his browser open.
The load on the server depends on:
The amount of work the php does each time it is called
and
The number of users you expect
Depending on what the server is doing, you may well be able to move the countdown logic into the client javascript, with the server just calculating the initial values. You can then use a timer in javascript to update every second, calculating the difference between the current time and the starting values.
Depends on your server and how optimised your PHP endpoint is... its a very conditional question.
However for what your doing, I would also suggest doing it all from JS.. even with birthdays, I would set a JSON object in the markup with all the birthdays that are recorded, then you can do it all client side... maybe call ajax every 5-10 minutes for any new birthdays that may be added... depends on what your application is.
I used setInterval, and checked if the remaining time equals zero. Then I rerun the ajax function.
thank you, all :) you were helpful after all ;)
if I understand, you want to call your server every second to update your time.
Can't you just :
Call your server to get the actual time
List item 2 - Process with a JS setInterval(functionIncrementAndUpdateDate, 1000); ?
You could use Keith Wood's countdown timer: http://keith-wood.name/countdown.html
It is extremely easy to use and no need for AJAX. All you have to do is include the plugin file and write:
<div id="timer"></div>
$(document).ready(function() {
$('#timer').countdown({
until: '<?php echo date("h:i:s"); ?>' // change this to New Year or a Birthday from DB
});
});
Demo: http://jsfiddle.net/tqyj4/436/
I'm working on a web app which must measure the time user needs to do something. I can't simply use javascript time object, because the user may change system time to cheat and fool the app. I'd need some way to prevent this.
I would make the web app send heartbeats or any other form of signals back to the server side. Then you can construct some metrics like duration = end - start
Accounting for the round trip client-server communication, this isn't suitable for ms resolution measurements, obviously.
Note : It's not a good idea to just read the time from a "trusted" web service into your client side app, you can't really guarantee the app wouldn't temper with it. (One of cardinal rules in client side dealings, is to not trust its input, e.g. for validation, you still need server-side validation on top). However if you just send signals to the server, log its timestamp using the server's clock, you are a lot safer.
Calculate time on the server side.
The client user cannot futz with that (at least they should not be able to)
Then you have to do it on the server side. Everything that happens on the client is manipulable.
One way would be to do ajax calls and measure the time in php or other server sided scripts.
A lot of this depends upon what time measurement accuracy you need.
If you are measuring long times (a minute or longer) and just need accuracy to within a minute, then using an ajax call to fetch a remote server time is clearly a more foolproof way than any client-side clock measurements.
If you are trying to measure shorter times in under a minute, then you will need to use the local clock to achieve any sort of accuracy. For that, you can check if the local computer's clock has been messed with using the following type algorithm:
Send a remote request to a server to get the current time. This could be either a publicly available time resource or your own server.
Get the current time on the local computer.
Calculate the offset between those two times. What you are looking for is that there is no significant change in the offset.
Using local computer time, mark the start of the local operation
User does their operation.
Get current time on the local computer to mark the end of the local operation
Get remote time again.
Get the current time on the local computer
Calculate the offset between local and server time. Allowing for a small difference in the amount of time it took to retrieve the remote time, see if the difference is relatively the same as the previously calculated difference. If this difference is not the same, then the local clock has been messed with.
Note, because you can't instantaneously get the remote time (there is always an indeterminate delay time in retrieving it), there is an inherent inaccuracy here of a few seconds in verifying that the local clock has not been messed with. The inaccuracy is not in measuring the local operation, just in verifying that the local clock hasn't been messed with.
So ... this technique works best for detecting clock manipulations that are more than a few seconds, not smaller manipulations.
If I make a live countdown clock like ebay, how do I do this with django and sql? I'm assuming running a function in django or in sql over and over every second to check the time would be horribly inefficient.
Is this even a plausible strategy?
Or is this the way they do it:
When a page loads, it takes the end datetime from the server and runs a javascript countdown clock against it on the user machine?
If so, how do you do the countdown clock with javascript? And how would I be able to delete/move data once the time limit is over without a user page load? Or is it absolutely necessary for the user to load the page to check the time limit to create an efficient countdown clock?
I don't think this question has anything to do with SQL, really--except that you might retrieve an expiration time from SQL. What you really care about is just how to display the timeout real-time in the browser, right?
Obviously the easiest way is just to send a "seconds remaining" counter to the page, either on the initial load, or as part of an AJAX request, then use Javascript to display the timer, and update it every second with the current value. I would opt for using a "seconds remaining" counter rather than an "end datetime", because you can't trust a browser's clock to be set correctly--but you probably can trust it to count down seconds correctly.
If you don't trust Javascript, or the client's clock, to be accurate, you could periodically re-send the current "seconds remaining" value to the browser via AJAX. I wouldn't do this every second, maybe every 15 or 60 seconds at most.
As for deleting/moving data when the clock expires, you'll need to do all of that in Javascript.
I'm not 100% sure I answered all of your questions, but your questions seem a bit scattered anyway. If you need more clarification on the theory of operation, please ask.
I have also encountered the same problem a while ago.
First of all your problem is not related neither django nor sql. It is a general concept and it is not very easy to implement because of overhead in server.
One solution come into my mind is keeping start time of the process in the database.
When someone request you to see remaingn time, read it from database, subtract the current time and server that time and in your browser initialize your javascript function with that value and countdown like 15 sec. After that do the same operation with AJAX without waiting user's request.
However, there would be other implementations depending your application. If you explain your application in detail there could be other solutions.
For example, if you implement a questionnaire with limited time, then for every answer submit, you should pass the calculated javascript value for that second.