Javascript - best of 2 ways to create a simple clock - javascript

So I'm creating a clock for my website, and I have thought of 2 approaches to it..
1)
var today = new Date();
this.start = function() {
this.update();
setInterval(this.update,1000);
}
this.update = function() {
today.setSeconds(today.getSeconds() + 1);
}
or
2)
var today = new Date();
this.start = function() {
this.update();
setInterval(this.update,1000);
}
this.update = function() {
today = new Date();
}
Which would be better? Generating a new date every second or just updating? (or perhaps a third approach)

It's much better for you to use new Date() for each loop because the interval used on setInterval will not be 100% constant.
new Date() will be accurate regardless of setInterval variances
Here's a snippet from an answer I gave a couple days ago. It explains the issue with using setInterval with fixed-value incrementing (or decrementing).
Beware of creating timers that increment with a fixed value
In your code, you have
setTimeout(() => this.count--, 1000);
The intention is for you to decrement your count property once every second, but this is not the behavior you will be guaranteed.
Check out this little script
var state = {now: Date.now()};
function delta(now) {
let delta = now - state.now;
state.now = now;
return delta;
}
setInterval(() => console.log(delta(Date.now())), 1000);
// Output
1002
1000
1004
1002
1002
1001
1002
1000
We used setInterval(fn, 1000) but the actual interval varies a couple milliseconds each time.
The problem is exaggerated if you do things like switch your browser's focus to a different tab, open a new tab, etc. Look at these more sporadic numbers
1005 // close to 1000 ms
1005 // ...
1004 // a little variance here
1004 // ...
1834 // switched focus to previous browser tab
1231 // let timer tab run in background for a couple seconds
1082 // ...
1330 // ...
1240 // ...
2014 // switched back to timer tab
1044 // switched to previous tab
2461 // rapidly switched to many tabs below
1998 // ...
2000 // look at these numbers...
1992 // not even close to the 1000 ms that we set for the interval
2021 // ...
1989 // switched back to this tab
1040 // ...
1003 // numbers appear to stabilize while this tab is in focus
1004 // ...
1005 // ...
So, this means you can't rely upon your setTimeout (or setInterval) function getting run once per 1000 ms. count will be decremented with much variance depending on a wide variety of factors.
To work around this, you need to use a delta. That means before each "tick" of your timer, you need to take a timestamp using Date.now. On the next tick, take a new timestamp and subtract your previous timestamp from the new one. That is your delta. Using this value, add it to the Timer's total ms to get the precise number of milliseconds the timer has been running for.

Related

ReactJS: Continue timer in the background?

I have a create-react-app that has a setInterval that runs a tick() function every 1000 millisecond. The tick() function decrements the sessionTime state by one. It works perfectly fine when the browser tab is in the foreground but it loses count in the background (not counting after a certain period). How do I allow it to continue running? Is this even the right approach to a timer in React?
You might be running out of your time budget?
Anyway, a more reliable way is not to rely on the interval being a specific time; check current new Date() every time you execute your tick, calculate how much time has passed since last tick or since a certain remembered start time (or remaining to certain target time), and act accordingly.
For example, if you want a session to expire in 30 minutes,
let now = new Date();
const second = 1000;
const minute = 30 * second;
let expiryTime = new Date(now.getTime() + 30 * minute);
and then in your tick just check whether new Date() > expiryTime. This way, it does not matter how often your tick routine runs.

Run JS function every new minute

So I've got this JavaScript clock I'm working on and I want it to be perfectly synced with the clients' system clock. I know how to get the current time using a Date object and I know how to run the update function every 60000 milliseconds (1 minute). The thing is that the client might load the page when half a minute has already passed, making the clock lag behind with 30 seconds. Is there any way to just run the update function when the minute-variable actually changes? (I only want minute-precision.)
How I get the current time:
var time = new Date();
var currentHour = time.getHours();
var currentMinute = time.getMinutes();
How I run the update function every 60000 ms:
setInterval(update,60000); //"update" is the function that is run
When the user logs in, get the current time and seconds of the minute, subtract 60 to get the remaining seconds, then multiply to set the timer
var time = new Date(),
secondsRemaining = (60 - time.getSeconds()) * 1000;
setTimeout(function() {
setInterval(update, 60000);
}, secondsRemaining);
First, you have to understand that timers in javascript are not guaranteed to be called on time so therefore you cannot be perfectly synced at all times - javascript just isn't a real-time language like that. It is single threaded so a timer event has to wait for other javascript that might be executing at the time to finish before a timer can be executed. So, you must have a design that still does as best as possible even if the timer is delayed (called later than it's supposed to be).
If you wanted to try to stay as close to aligned and do the fewest screen updates and be the most friendly to mobile battery life, I'd suggest this self-aligning code which realigns itself on each tick based on the time remaining until the next minute change:
function runClock() {
var now = new Date();
var timeToNextTick = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
setTimeout(function() {
update();
runClock();
}, timeToNextTick);
}
// display the initial clock
update();
// start the running clock display that will update right on the minute change
runClock();
This has the advantage that it only calls the update once on the next minute boundary.
Working demo: http://jsfiddle.net/jfriend00/u7Hc5/
var time = new Date();
var currentHour = time.getHours();
var currentMinute = time.getMinutes();
var currentSecond = time.getSeconds();
var updateinterval = setInterval(startTimer,(60-currentSecond)*1000);
function startTimer(){
clearInterval(updateinterval);
setInterval(update,60000);
}
function update(){
var time = new Date();
console.log(time.getSeconds());
}
I would set an interval to run each second, then check if time.getSeconds() == 0. This way you could execute an action whenever a new minute starts, based on the client time.

JS - Timer Is Running Slow

I have written a simple JavaScript timer, but I've noticed that it runs at 1/3 speed. This timer is suppose to keep track how many MS has passed. I am unsure what I have done incorrectly.
http://jsfiddle.net/m3vYc/
time = 10000;
timer = setInterval( function() {
time--;
$('#timer').text(time);
}, 1);
Your error is in assuming that your computer can keep timers of 1 millisecond.
Some browsers will use the computer's clock, which in Windows ticks every 16ms (1/60th of a second, ie the framerate of your screen). Others will override this for a somewhat more accurate 3ms, which is why you are seeing a result of 1/3 speed.
Instead, use Delta Timing:
var start = new Date().getTime();
setInterval(function() {
var now = new Date().getTime();
var elapsed = now-start;
var timeleft = 10000-elapsed;
$("#timer").text(timeleft);
},25);
Demo
Firing a function on each millisecond will clog your browser pretty fast. After all, jQuery is performing a DOM manipulation and it does take a real timelapse, even if tiny.
You should:
fire it with a higher interval,
instead of keeping track of a global time variable, use the browser current timestamp with new Date().getTime()
Add the function to the stack to avoid itself from becoming an obstacle
something like:
var time=new Date().getTime()+10000;
timer = setInterval( function() {
setTimeout(function() {
var timediff=time-new Date().getTime();
$('#timer').text(timediff);
},0);
}, 100);
setting timeout to 0 will fire it inmediately unless there's something enqueued in the stack.

Run a Function For Each Milliseconds

I am trying to run a function for each milliseconds, In order to achieve so, I just preferred setInterval concept in javascript. My code is given below,
HTML:
<div id=test>0.0</div>
Script:
var xVal = 0;
var xElement = null;
xElement = document.getElementById("test");
var Interval = window.setInterval(startWatch, 1);
function startWatch(){
xVal += 1;
xElement.innerHTML = xVal;
}
so the above code is working fine. But while I am testing the result with a real clock, the real clock requires 1000 milliseconds to complete 1 second, at the same time the result require more than 1000 milliseconds to complete a second.
DEMO
Can anybody tell me,
Is there any mistakes with my code? If yes then tell me, How to display milliseconds accurately.?
There are no mistakes in your code, but JavaScript timers (setInterval and setTimeout) are not precise. Browsers cannot comply with such a short interval. So I'm afraid there is no way to precisely increment the milliseconds by one, and display the updates, on a web browser. In any case, that's not even visible to the human eye!
A precise workaround would involve a larger interval, and timestamps to calculate the elapsed time in milliseconds:
var start = new Date().getTime();
setInterval(function() {
var now = new Date().getTime();
xElement.innerHTML = (now - start) + 'ms elapsed';
}, 40);
You can't. There is a minimum delay that browsers use. You cannot run a function every millisecond.
From Mozilla's docs:
...4ms is specified by the HTML5 spec and is consistent across browsers...
Source: https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout#Minimum.2F_maximum_delay_and_timeout_nesting
The DOM can't actually update 1000 times per second. Your monitor can't even display 1000 frames in one second, for that matter. Calculate the difference between the start time and current time in milliseconds within your function and use that:
(function(){
var xElement = document.getElementById("test");
var start = new Date;
(function update(){
xElement.innerHTML = (new Date - start);
setTimeout(update, 0);
})();
}();
Updated fiddle
You can't do so using your method because of the delay rendering the HTML and running the interval. Doing it this way will display the time correctly at about 60FPS.
http://jsfiddle.net/3hEs4/3/
var xElement = null;
var startTime = new Date();
xElement = document.getElementById("test");
var Interval = window.setInterval(startWatch, 17);
function startWatch(){
var currentTime = new Date();
xElement.innerHTML = currentTime - startTime;
}
You might also want to look into using requestanimationframe instead of a hardcoded setInterval like that.
The setInterval callback probably does not happen with millisecond accuracy, since the thread the timer is running on might not even actually be running when the time is up, or the browser throttles events, or any other of quite a few things.
In addition, since most Javascript engines are single threaded, what the implementation of setInterval might do is once it triggers, run your callback, and then reset the clock for the next call. Since you're doing some DOM manipulation, that might take several milliseconds on its own.
In short, you're expecting a Real Time Operating System behavior from an interpreter running inside of another application, on top of what is more than likely not an RTOS.
I had the same question and couldn't find any working solution, so I created one myself. The code below essentially calls five setTimouts every 5 ms, for each ms between 5 and 10. This circumvents the minimum 4 ms constraint, and (having checked in Firefox, Chrome, and Opera) works fairly well.
const start = performance.now();
let newNow = 0;
let oldNow = 0;
const runner = function(reset) {
// whatever is here will run ca. every ms
newNow = performance.now();
console.log("new:", newNow);
console.log(" diff:", newNow - oldNow);
oldNow = newNow
if (newNow - start < 1000 && reset) {
setTimeout(function() {
runner(true);
}, 5);
for (let i = 6; i < 11; i++) {
setTimeout(function() {
runner(false);
}, i);
}
}
};
runner(true);
It could of course be written more elegantly, e.g. so that you can more easily customize things like the graduation (e.g. 0.5 ms or 2 ms instead of 1 ms), but anyway the principle is there.
I know that in theory you could call 5 setIntervals instead, but that would in reality cause a drift that would quickly ruin the ms precision.
Note also that there are legitimate cases for the use. (I for one need continual measurement of touch force, which is not possible otherwise.)

Javascript event triggers based on local clock

I have a scenario where one client PC will be driving multiple LCD displays, each showing a single browser window. These browser windows show different data which is on an animated cycle, using jquery.
I need to ensure that both browsers can be synched to rotate at exactly the same time, otherwise they'll animate at different times.
So my question is - can I trigger jquery to alternate the content based on the local PC clock?
eg each time the clock seconds == 0, show version 1, each time clock seconds == 30, show version 2 etc?
This is (in my experience) the most precise way of getting timers to trigger as closely as possible to a clock time:
// get current time in msecs to nearest 30 seconds
var msecs = new Date().getTime() % 30000;
// wait until the timeout
setTimeout(callback, 30000 - msecs);
Then, in the callback, once everything is done, do the same again to trigger the next event.
Using setInterval causes other problems, including clock drift. The calculation based on the current time accounts for the time executing the callback itself.
You'll still also need to use Date().getTime() as well to figure out which frame of your animation to show.
The whole thing would look something like this:
function redraw() {
var interval = 30000;
// work out current frame number
var now = new Date().getTime();
var frame = Math.floor(now / interval) % 2; // 0 or 1
// do your stuff here
.. some time passes
// retrigger
now = new Date().getTime();
setTimeout(redraw, interval - (now % interval));
}
redraw();
working demo at http://jsfiddle.net/alnitak/JPu4R/
The answer is: yes you can.
Use Date.getTime() to monitor time
Trigger your js function every 30 seconds
You could do something like this.
This way, no matter when you launched the different browsers, their rotations would be in sync.
var t=setInterval("check()",1000);
function check(){
var d = new Date();
if(d.getSeconds() == 0)
{
alert('do something');
} else if (d.getSeconds() == 30)
{
alert('do something else');
}
}
Why not launch one window from the other - that way the parent window will have complete control over when the animation starts, because they are in the SAME PROCESS. No clocks required.

Categories

Resources