I'm developping an offline web application and I'm trying to find any datetime available, on the device running the app, that is not editable by the user. I have to be able to access it through javascript. The reason is that I want my application to be insensitive to time change hack on mobiles. Any ideas ?
You can't throught javascript, maybe you can limit the hack by launching a javascript timer at the launch of the webapps and use it to check the time instead of the time of the device ? It depends on the accuracy you want but something like that will be updated every second :
var time = new Date();
function loop(){
setInterval(function(){ time=new Date(time.getTime() + 1000);loop(); }, 1000);
}
loop();
So the time variable is the real time elapsed since the launch of your apps.
Downside of this, it will use ressources...
Related
I'm trying to develop a simple LiveDateTime object that's reliable, accurate and somewhat independent of the client system date as far as the updating of the time goes.
I've tried several solutions:
Taking the server date and the time difference with the client system date to calculate the elapsed time and update the time accordingly every 150ms.
Taking the client system UTC date and increase it with a second every 1000ms with setInterval() or setTimeout(). Also tried it with a self-correcting delay loop.
Some similar variants of the above.
All of the above didn't meet the requirements, either because if the client system date was changed it would set the live time off as well, or just the delay of the loop was inaccurate and drifting off over time.
So, I decided to just go online and search for some popular websites that have what I want already implemented and working. I stumbled upon this Greenwich Mean Time example that's reliable, accurate and somewhat independent of the client system. If I change the date of my system, the date that they display is unaffected.
Upon inspecting their code I found it hard trying to understand what they are doing that I could replicate, because either their code is badly written or I'm not that advanced enough to understand it.
I do know that they use AJAX calls (request.js) to the server for something (maybe the server time). And that they're using a setInterval(func, 150) and a whole bunch of other presentational methods of which I think aren't the core of the live time's functionality.
Anyone who could help me figuring out the core of the functionality of their accurate live time? If I can figure that out, from there it would be easy for me to replicate.
The example is combined with a server-side language to get the server time. The time is directly written into the JS by PHP, in this line for example:
var ServerDSTCheck = new Date(parseFloat(1426849548940.7)).getTime();
That float 1426849548940.7 comes from the server, and that's why it's not affected by the client machine time. The AJAX call returns the same thing in intervals to maintain the server time, so it can't be messed up on the client and to avoid the client lag.
That's the base of what you need. The rest of the code is about daylight savings, timezone compensation and presentational stuff.
As I understand, you want independent clock in JS, right? It's pretty simple:
Make an ajax request to your server, while the script is loaded by the user, to get current time (UNIX).
Set interval for example 1 sec, and just increment your time, that you get in pt 1, for the interval you choose.
When user change his time on local machine it wouldn't affect the script, also refreshing script would again load time from your server.
Since js timers are extremely unreliable by default I'd say you must use two parallel intervals.
One, which will correct the frontend's time drift against server time and other which will fill in the blanks on the frontend (to not strain the server and user's connection).
var time = Date.now(); // Or initial server time
var oldTime = Date.now();
var newTime = oldTime;
var feInterval = setInterval( function() {
// Incrementing "time" by whatever frontend difference, aka Delta time
time += ( newTime = Date.now() ) - oldTime;
oldTime = newTime;
}, 40 );
var beInterval = setInterval( function() {
// Fetch server UTC milliseconds and overwrite "time".
// Above interval will just use that as a new base time.
var serverTime = Math.random() * 10000000000; //use Ajax to get server time.
time = serverTime;
}, 10000 );
setInterval( function() {
// Do something with "time"
// This interval is just for demo, you don't need it in general - use your own "time" consumer.
console.log( 'Fairly correct time (random each 10 seconds):', new Date ( time ).toString() );
}, 40 );
I guess there is someone else trying solve the same problem,
check out below page,
show server time including timezone offset
I am building a webapp where user have a ranking based on their twitter activity and their activity on my website.
Therefore I'd like to update their rank every five minutes, pulling their latest activity from twitter and update it in my database. I was thinking of using something like this:
var minutes = 5, the_interval = minutes * 60 * 1000;
setInterval(function() {
// my update here
}, the_interval);
However, I have several questions about this code:
where should I save it to make sure it is run?
will it slow my program or is it a problem to pull data out of twitter every five minute? Should I use their streaming API instead?
Note: I am using mongoDB
I'd suggest that you create a scheduled task/chron job/etc. (depends on your host OS) to call a separate Node.JS application that performs the specific tasks you want to do periodically and then it would exit when complete. (Or you could use a ChildProcess potentially as well).
While Node.JS is async, there's no need, given the description you provided, to perform this work within the same application process that is serving a web application. In fact, as it sounds like "busy work", it would be best handled by a distinct process to avoid impacting directly any of your interactive web users.
The placement shouldn't really matter as Node is asynchronous.
I want to implement an idle time-out for the web application that we are building. I had earlier achieved this using AsynchronousSessionAuditor from codeplex, which essentially looks for the formsauthentication and session cookie timeout by constant polling.
But it has a draw back of not respecting the client side events, it will look for only last postback to decide when to log off.
The jquery plug jquery-idle-timeout-plugin from erichynds solves this issue of client side events but suffers from another drawback that is not able to recognise user is active on some other tab.
Is there anyone already fixed the TABBED browsing issue with jquery-idle-timeout-plugin already? Or is there any better approach of application time out for web applications (by the way this web app is build using asp.net f/w)
If I understand your question right, it is not possible, since there are no events triggered in javascript for activity outside of the current window/tab.
Unless you have a addon to go along with your website for each browser, which could monitor all activity in the browser, but that is not really a practical approach.
Well, you'd have to code it by hand, which is not really hard. You can use the onfocus and onblur functions to do something like this:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (!window.isActive) { /* Check for idle time */}
}
If you make a little search you can find that varaieties of this question have already been asked and answered, you can probably find a solution you can implement with one of the plugins you mentioned.
Try:
Run setTimeout only when tab is active
or
How to tell if browser/tab is active
EDIT--> ADDED:
Or I'd try a different approach. You could create a cookie with some hash and save that hash in your DB with a timestamp that updates whenever the window is active (you could check every 5 seconds or something, it's not an intensive request)
Then, do another check before(but in the same request) to see how much time has passed since the last timestamp and log them out if necessary.
it won't log them out isntantly when time has passed, but it will when they try to access the site either by opening it again or by focusing on the tab/window.
I have a program written in c++ that reads values from this board. Anyways that part is not important. What I have is data that is constantly changing and I will like to graph that data. I was hoping to use a web browser to display the data since there are so many open source graphs and charts out there written in JavaScript. So my problem is to send data to the browser from my c++ program
I already investigated and UDP is not available in browsers yet so I will have to use TCP. TCP websockets are not that fast and I was thinking about using html5 localstorage instead. By that I mean have my c++ program write to the database on localStorage then javascript will wait for the value of that variable to exist and invent some sort of protocol that will make that work. Local storage is really fast for example :
<script type="text/javascript">
var counter = 0;
window.onload = function () {
function Test() {
counter++;
localStorage.p = counter + ""; // perform write
var read = localStorage.p; // perform read
if (read == "5000")
alert((new Date() - now)); // shows 45
else
Test(); // loop again
}
var now = new Date();
Test();
}
</script>
that script takes 54 milliseconds and it reads AND writes 5000 times! That means that instead of creating a plug-in for the browser next time I will just implement some sort of protocol that will enable me to exchange information using the localStorage. For example I could have the browser waiting for the variable x to exist. Once it exist I then creates a variable y by the browser notifying the c++ program that it is ready to receive data and so on. localStorage is just a sqlite database located on C:\Users[USER]\AppData\Local\Google\Chrome\User Data\Default\Local Storage
I haven't seen anyone online that uses this approach. Maybe it is too dangerous and Sqlite cannot handle multiple threads that good and I will be wasting time creating this program.
So should I start implementing this protocol? Should I use websockets? Or should I give it a try to https://stackoverflow.com/a/10219977/637142 ?
I would go with node.js as middleware from your C++ to the browser, instead of using directly websocket (been there done that) go with http://socket.io/ that will make your life much easier :)
here is my question:
I've a website that works only during the night (after 21:00 until 24:00)
I have a button that says "Enter", but i want that button to alert() a message such as 'The website is not available yet'.
But to do so it must check the time so in pseudocode:
if (time is less more than 21:00 and less than 24:00) {
return true;
} else {
alert('the website is not available yet');
e.preventDefault;
return false;
}
But I don't understand how I can do that in terms time difference, in any day,
any hint?
thank you guys!
new Date().getHours()
will return current hour (13 when I am writing this at 13:42). However this solution has several drawbacks:
it uses system time, changing the time in the computer will fool your script
it uses system time zone, consider getUTCHours()
it can be easily bypassed by disabling JavaScript or modifying the script on the fly
Thus consider fetching time from the server when rendering the page and repeating the test on the server side when user enters (to make sure the check was not bypassed).