JavaScript Countdown Timer Using Server Time - javascript

I'm trying to create a countdown timer that's based on a time on the server.
I originally had the server set the time left, and just did a setTimeout for 1 second that would decrement the time.
I found 2 problems with this:
There is a lag from the server setting the time until the client's page is rendered and the JavaScript begins to run. The lag amount depends on the speed of the users internet connection and computer/JavaScript engine.
I think setTimeout of 1 second may have been getting behind a little on slower computers.
I changed it so the server would set the ending time and the JavaScript on the client would take the time (in UTC) and calculate the remaining time left. It would then do this on every setTimeout callback. This makes the time and countdown perfect. If the client has a fast computer/JavaScript engine, the timer stays on page. If the computer/JavaScript engine is slower, you may see a second be skipped here and there, but the time is never off.
I found 1 problem with this method so far:
Every client's clock may be different.
So, the time left may be a couple seconds, or 30 seconds, or even days off if the clients time is not correct on their computer.
Is there a way that I can have the time left be exact based on the server's ending date?

I don't know what kind of resolution you need, but given network and page rendering latencies, it's going to be impossible to get client-server agreement to much better than a second. I would suggest you do an ajax poll every 5 or 10 seconds, and adjust your timer accordingly. There is also comet which is essentially "reverse" ajax, which can push the times to the client. But either way, you still have network and renderign latencies to contend with.

Related

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.

Audio sync, call function every 1 / 44.1 millisecond

In JavaScript, is it possible to call a function playing 10 different wav sounds at 44.1 kHz and call that same function again in (1/44100)*(128/60)*16 seconds with a 1/44.1 millisecond precision preferably with chrome/safari and in that case how?
I'm looking at making a music loop machine playing a few simultaneous loops. The precision is needed otherwise there will be unwanted hearable issues with the sounds (phasing).
Robert,
It's possible to measure time with high accuracy - via performance.now() - but you cannot get a callback with that kind of precision. In fact, in light of layout passes and JavaScript execution in the main thread, and the ever-looming threat of garbage collection happening in the main thread, you can't get anywhere NEAR even millisecond precision; you generally ought to be planning on potential interruptions in the tens of milliseconds for robustness.
The answer to this is to use scheduling, particularly in the Web Audio API - I see that you saw the article I wrote about this a year ago on HTML5Rocks (http://www.html5rocks.com/en/tutorials/audio/scheduling/), but you missed the significant piece - you shouldn't be calling
audioSource2.noteOn(0, 0.1190, 1.875);
you need the time offset to schedule it ahead appropriately:
audioSource2.noteOn(time, 0.1190, 1.875);
If you look at my original code, that's how I'm scheduling the oscillator ahead of time. The scheduler runs in a "slow" callback loop - being called only every 100ms or so - but schedules ahead a few beats. If you truly need to mute notes that may already be scheduled in the next 1/10th of a second, then you can keep a node in the middle to disconnect().
I would take a look at either DOM High Resolution timestamp, which can be accessed with window.performance.now(), or request Animation Frame, with window.requestAnimationFrame
You can use this library which I have written : https://github.com/sebpiq/WAAClock
It lets you schedule things precisely and easily and also provides useful functionalities such as : cancel event, change tempo, ... everything necessary for a loop machine. Under the hood, it implements the tricks explained in this article (already linked by other people) : http://www.html5rocks.com/en/tutorials/audio/scheduling/
If by loop machine you mean continuously looping a few samples (and not a drum machine, where you just play a sample at a point in time), you might also want to look into this : https://github.com/sebpiq/WAATableNode

How to update visually a live tile every minute of a Windows Store App in JS/HTML/CSS?

I would like the live tile of my app to be updated everytime the user opens the Start screen as its live tile's feature is "only" visual (doesn't need to be on lockscreen or perform specific logic in the background for example)
On the windows Store you can find "watches" app which will show you the time on the start screen via their app live tile usually with a granularity of every minute not more. This would be perfect for me.
Those apps seems to have then a much more precise time interval than those famous 15 minutes, and they do run as a background task (those apps ask for the permission to).
So what does actually happen every 15 minutes? How come those tiles are not constrained to this 15 minutes interval? I heard they might use a notifications queue, but they still need to be updated on 1 minute basis...
Thanks a lot for help!
You can use TileUpdater.addToSchedule to schedule up to 4096 notifications. So, I imagine one approach is:
Set up a maintenance task to run at some interval (don't need to
be on the lock screen for this).
When the task runs:
2a. Clear out your notification queue.
2b. Schedule a bunch of notifications, one for now + 1 minute, one
for now + 2 minutes, etc (register fewer than 4096, and don't
register more than you really need).
Your maintenance task could be scheduled to run daily, but you could schedule 2 days worth of notifications in case it doesn't get run in time.
The main downside with this is that if the user is on battery power for more than 2 days (or however far out you schedule them), your notifications will stop until they plug in and your maintenance task is allowed to run.
If you don't need an update every single minute, you could schedule them farther into the future (i.e. a week or more, if you did every 5 minutes).
Notice the types of notifications found here.
The 15 minute limitation you mention is discussed under the periodic notifications found here.
Local, scheduled and push notifications can probably all do what you require, although I'm less sure about the scheduled notifications since I think there is a limit on the number of these you can have queued up at one time.
(I think - haven't tested this) A local notification can be used to send tile updates from a background task, but this has the limitation that your app needs to be running to have this work.
Push notifications come from a cloud service and can happen while your app is not running. Unfortunately this requires a cloud service.
My team member here at Microsoft Michael Palermo (blog here) has a similar app called Tile of Time
It seems like a very simple app, but the trick here as I understood it from him was to schedule a background task out for the next fifteen minutes for every one of the updates and ensure there are no duplicates. It seems like a lot, but that's to workaround the time constraints provided for background tasks.

Is there a harder to break way to obfuscate a javascript function than hieroglyphy?

I'm developing an online chess variant game. I want to create a javascript function that has the purpose of communicating to the server on behalf of the player the exact time spent on a move.
This message will be encrypted, of course, but in order to trust this function, I want to obfuscate it to the point that I can rely on the obfuscation algorithm.
I only know a few obfuscation algorithms, hieroglyphy being the most interesting. But it isn't unbreakable. Speed of execution and size are not critical, I can deduct the time spent by the function that sends the message in that same function, and the size can be even up to 2MB.
I'm pretty sure that there is no unbreakable algorithm because as long as it is required to run in a browser, anyone with enough patience can take it piece by piece and see what it does.
Do I have an alternative that would require more effort and time from a user with bad intentions?
Edit I've done some tests in every browser on WindowsXP and it appears that in FF, IE, Opera and Chrome the setTimeout function will trigger after a delay that is passed as the second parameter, regardless of any changes to system time during the delay. If no other information is presented to suggest otherwise, the logical conclusion would be that time can be measured client-side regardless of system time changes, using the setTimeout function but not the Date() object, up to a precision given by the setTimeout delay time.
Hamish mentioned in an answer below that modifying the browser date/time APIs is trivial. In that case, the javascript code is vulnerable to a modification that will increase the setTimeout real delay time. Some code should be set in place so that the server should start suspecting of cheating someone who has unreasonable lag time. This will always be a problem if lag time isn't included in thinking time.
There's a reason I can't use server side timing. The lag times would sometimes exceed a reasonable amount and that will leave users dissatisfied. And sometimes the lag can make all the difference.
Which brings me back to the original question. I'm looking for the best obfuscation method, where best is measured in the effort an attacker has to make to deobfuscate. Ideally, I would want to change the obfuscation algorithm faster than an attacker can deobfuscate, and then never to use that algorithm again or use it rarely, at a time the attacker won't expect.
I could set my computer's clock to three hours ago and your script would happily send -10800 seconds. NEVER rely on JavaScript to handle information in a trusted manner. Use your server-side code to time the difference between when the player's turn started and when they made their move, and absolutely keep a representation of the game on the server and make sure the move is valid.
Obfuscating your code doesn't help, for two reasons:
Users can still inspect the messages being sent from the browser to the server. You would also have to sign the message somehow, to prevent it being intercepted and modified. Generally, it will be even easier to unpack the message than the function used to generate it.
You're trying to measure the time taken on the move, which means your obfuscated function still has to trust the system clock and the browser date/time APIs. Both are trivial to modify.
A sensible solution would be to measure the time messages are sent and received on your server, and measure the latency of the connection to correct for transmission speeds (if you need to be very accurate).

Why is there a difference between JavaScript and PHP timestamp

I have created a JavaScript timestamps and also a PHP timestamp. There is about 170 sec difference between them.
1302162686 PHP - time()
1302162517 JavaScript - Math.round(new Date().getTime() / 1000)
Can anyone please tell me why I'm having this issue?
PHP is executed on the server side, and in your example, JavaScript works on the client-side.
Both sides have their own time configuration. For the server, time zone settings etc. will stay the same (unless you change them), but the server has no idea which time zone the current visitor is in. There’s no way for you to control that.
If I change my system clock on my laptop, it will influence client-side JavaScript date/time, but your server timer won’t be affected.
PHP and JavaScript, both look at the system time. Whose system? The one they are running on. The server could be located in another country with different time, hence the difference.
Also, the client's (or less often, server's) clock could be incorrect.
One way, which I often use to counter this problem is like this:
var referenceTime = new Date('<?php echo date("M n, Y"); ?>');
// referenceTime is now the same as server time
PHP looks at the system time, which is the server running it.
JavaScript looks at the client's system, which could be any time.
php uses the time on your server, javascript will use the time on the client (users) machine.
Mathias is correct. Generally this should not happen with that big a difference because modern computers recognize their clocks drift over time and employ protocols such as NTP to keep their clocks in sync.
Nevertheless you should never assume the time at client and server is the same, for two reasons:
Some clients/servers don't have clock adjustments (such as NTP) and their clocks drift away over time
More importantly, many users/admins can be clueless or late in setting their time zone or adjusting daylight savings times, so the time given to you may be accurate to a second but be several hours off.
When comparing/calculating times, I would rely on the server only. You have no control over the client.
If you are concerned about consistency for whatever purpose, I recommend using the server as your time source and do timezone conversions if necessary:
This may be of interest: handling timezone conversion with php

Categories

Resources