Bind events to timestamp in javascript - javascript

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).

Related

How can I access hardware time from browser

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...

Replicating this Live Time core functionality

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

What is the best way to implement idle time out for web application (auto log off)

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.

Once callable function in Javascript

I am developing a quiz component in Javascript and I have a startTimer() function in it which starts a countdown based on the value passed to it.
The function is called when the page loads and the quiz starts.
I don't what users to call the function again and alter the quiz time.
Is it possible to detect that the function is called a second time???
Any user can just disable JavaScript in their browser.
I would suggest that you record the time between the page being served and the answers coming back on the server and use that as the definitive source for how long they took. Perhaps allow a little buffer to compensate for network latency and page rendering time.
The JavaScript timer can be a nice UI feature to help the user know how much time they have left, but never trust a user interface, for a smart user will write his own UI (or in this case, configure the UI to not use JavaScript).
If you want to prevent people from changing any aspect of the quiz, you will have to implement the restrictions on the server.
It will be very hard, if not impossible, to prevent meddling with the quiz data on the client side.
Thanks everyone, I found this on net:
function createChance(){
var chanceLeft = true;
return function(){
if(chanceLeft){
console.log("This was the only chance you had.");
chanceLeft = false;
}
else{
console.log('Sorry: you already used your chance');
}
};
}
var chance = createChance();
chance();
// This was the only chance you had.
chance();
// Sorry: you already used your chance
any hacks for this????

Online Ticketing Purchase Timer

Can someone please guide me as to what is the best way to have the time restriction timer in one of my online application written in Classic ASP with MsAccess database.
Simple process..Once the user shops, the system redirects the user to enter the billing & shipping information where-in this timer is shown and valid for 10 minutes.
Initially I captured the server side time and added 10 minutes using Classic ASP's DateAdd function "DATEADD("n",10, TIME())" and then used JavaScript to match the current time with the expiry time. But since site can be accessed from any part of the world, so taking server time is not helpful as Javascript matching is taking local PC time, so it will never match.
Secondly, when the user refreshes the page, the 10 minute timer will restart.
Appreciate your help. It can be through Javascript or Classic ASP.
In page1, do this
session("shopping_time") = now
In the subsequent pages
do this,
session("current_time" ) = now
time_elapsed = datediff("n",session("current_time" ),session("shopping_time"))
if ( time_elapsed > 10 ) then
//do something
end if

Categories

Resources