setInterval slows down with tab/window inactive - javascript

I build a web app and I use setInterval with 500ms timer for some clock.
When the window is active the clock runs perfect, I use that:
var tempTimer = 0;
setInterval(function () {
goTimer()
}, 500);
function goTimer() {
tempTimer++;
$("#timer").val(tempTimer);
}
But the problem is when the window/tab becomes inactive - the interval is changed to 1000ms!
When i focus the window/tab again, it changes back to 500ms.
check this out: http://jsfiddle.net/4Jw37/
Thanks a bunch.

Yes, this behavior is intentional.
See the MDN article:
In (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2) and Chrome 11,
timeouts are clamped to firing no more often than once per second
(1000ms) in inactive tabs; see bug 633421 for more information about
this in Mozilla or crbug.com/66078 for details about this in Chrome.
And the spec says:
Note: This API does not guarantee that timers will run exactly on
schedule. Delays due to CPU load, other tasks, etc, are to be
expected.

You seem to want a timer that increments every half second. You can do that much more accurately by keeping track of the total time since you started and doing some math.
var tempTimer = 0;
var startedTimer = Date.now();
setInterval(goTimer, 250); // a little more often in case of drift
function goTimer() {
tempTimer = Math.floor((Date.now() - startedTimer) / 500);
$("#timer").val(tempTimer);
}
See this work here: http://jsfiddle.net/4Jw37/2/
So this does update every half second, but it doesn't need to. If it skips a few beats it will fix itself the next time it fires because it's recalculating each time based on the time since it started tracking. The number of times the function runs is now has no effect on the value of the counter.
So put in another way, do not ask how many times you incremented the count. Instead ask how many half second segments have passed since you started.

For time interval, Browsers may not behave similar for both active and inactive window.
What you can do, When you are setting the time interval you can save the timestamp(initial time). On window.onfocus, take on there timestamp (now) find the difference between initial time and now and use that update the tempTimer.

Related

SetInterval not running in Firefox when lost focus on tab/window

I have a setInterval function that do countdown of time.
startCountDownWorker() {
this.worker= setInterval(() => {
this.countDown--;
// When count timer reach zero
if (this.countDown === 0) {
// Clear decrement for count down
clearInterval(this.worker);
}
}
}, 1000);
}
The function was tested on Chrome,Firefox,Opera,Safari, its working fine on all except Firefox. When lost focus on Tab/Window on Firefox, the function stopped and only resume when I focus back on the Tab. Any ways to solve this issue ??
Browsers do apply a threshold to almost all timing functions when the page is blurred, so all these timed-out functions may only execute once in a while.
Not only this, but there is even an incoming Page Lifecycle API that is being drafted and which would add a discarded and a frozen state to the page's visibility, during which your script would not execute at all, until unfrozen.
So the best in your position, to be future proof and since you apparently only need a quite long interval, might be to handle the visibility changes and to record the time at which the page got blurred, then when it's focused back, to update your counter based on the actual elapsed time.
An other even more reliable solution would be to not actually hold an actual countDown value in your counter, but rather to always compute the delta between the starting time of that counter and now. This way, you don't rely on the precision of the browser's timers and you can adjust your timeouts between each tick.

setInterval timer be more slower when go another chrome tab

I build a countdown timer, so - When I stay in the countdown chrome tab, its work fine.
But when I go to another tab (while the countdown) running, its made it slower.
for example when you start countdown for 30 seconds, and you go to another tab for 10 seconds, when you go back to the countdown tab it will be in 24 seconds - instead of 20 seconds (its just example its very changeable).
stopper = setTimeout(progressCountdown, 1000);
the progressCountdown function its not needed here because its work fine when I in the countdown tab.
There is some option to fix that?
A timeout is not guaranteed to be run after exactly the given delay. In fact, there can be a number of reasons why the delay will be longer than the one you give, for instance if your web page or CPU is overloaded with work, or if it's throttled by the browser to save power and battery (which is what many browsers do with background tabs). MDN has a list with many reasons why these things may occur.
What seems to be your actual problem, however, is that you're using the timeouts to track time itself. This will often be very inaccurate due to the above problems. What you should do instead is to use a clock to keep track of the time spent before the timeout fires:
// performance.now() is a good way of measuring durations
let atStart = performance.now();
function timeoutCallback() {
let now = performance.now();
// milliseconds is accurate now matter how long the timeout actually took
// no matter if in foreground or in background tab
let milliseconds = now - atStart;
// number of seconds left
let secondsLeft = Math.ceil(30 - milliseconds / 1000);
console.log('Countdown: ' + secondsLeft);
if(secondsLeft > 0)
setTimeout(timeoutCallback, 1000);
}
setTimeout(timeoutCallback, 1000);

window.setTimeout behaviour when window not in focus [duplicate]

This question already has answers here:
How do browsers pause/change Javascript when tab or window is not active?
(3 answers)
Closed 9 years ago.
Here's the simplest code for reproducing I could think of:
ms = 30; // 1000 ?
num = 1;
function test()
{
num+=ms;
document.getElementById('Submit').value = num; // Using native Javascript on purpose
if (num < 4000)
window.setTimeout(test, ms);
}
test()
I set the ms (milliseconds between iterations) to 30, ran the script and moved to different tab on the browser.
Then I wait for about 10 seconds (the script should finish within 4 seconds) and came back to the tab.
If I used Firefox I saw that the script has not finished, and the numbers are still running (resuming from where I left them, I guess).
Which is annoying enough,
But if I changed ms to 1000 and repeat the above steps, when I come back to the tab I saw the script has indeed already finished.
(The script should still take 4 seconds to finish).
Namely, sometimes Firefox runs window.setTimeout even if the window is out of focus, and sometimes it doesn't. Possibly depending on the duration
On the other hand, this is not happening with Internet Explorer.
It keeps running the script even if the tab is not focused. No matter how I set the ms.
Is that due to some performance considerations of Firefox?
What exactly is happening?
How come such a basic thing is in consistent between browsers,
nowadays?
OR, am I working wrong? Is it a weird way for coding?
I'm just trying repeatedly change the DOM, in a delayed fashion, without using setInterval (because I'm changing the interval it self on the go).
And most important, how should I regard this?
I can't assume my user won't leave the tab.
I want to allow my user to leave the page for as mush as one might like.
If one leaves and come back after half an hour, he/she will see irrelevant animations on the page, still running.
Some of these animations are seen by all the users connecting to the page.
There is no need they will be synchronized in resolution of milliseconds, but I can't start them only when the user put the tab/window in focus.
I'm using Firefox 25.0.1, and IE 11. (Windows 7)
Most modern browsers (especially on mobile devices) suspend execution of scripts in tabs that are out of focus to save CPU cycles (for instance, this is why requestAnimationFrame was brought to life). In the case of timeouts, shorter intervals are actually changed to a different / higher value as the browser vendor sees fit.
What you can do to overcome this (if you really must know the interval between successive executions) is to set a timestamp when the timeout is activated, and compare it with the timestamp when the timeout handler is actually executed. Note that when you're animating it's best to calculate properties of the animated Objects by taking other application variables into account, rather than rely on the amount of calls a particular handler has had.
You could also attach listeners to the window for "(un)focus" Events to know when the user has "come back" to your application. In this event handler you can verify whether a timeout was pending and execute its callback manually, if you must do so.
see the difference: http://jsfiddle.net/qN6eB/
ms = 30; // 1000 ?
num = 1;
start = new Date();
function test()
{
num+=ms;
document.getElementById('Submit').value = num;
if (num < 4000)
window.setTimeout(test, ms);
else
document.getElementById('Time').value = new Date() - start;
}
test()
ms2 = 30; // 1000 ?
num2 = 1;
start2 = new Date();
dueTo = new Date(+new Date()+4000);
function test2()
{
num2+=ms2;
document.getElementById('Submit2').value = num2;
if (new Date() < dueTo)
window.setTimeout(test2, ms2);
else
document.getElementById('Time2').value = new Date() - start2;
}
test2()
setTimeout is not precise for timing. Because the timer doesn't interrupt the process, I'll wait for idle time. I don't know how the browsers are managing it, but an inactive tab probably has a lower priority.
I can think about two solutions :
- Try setInterval (I'm not sure if this will solve your problem or not)
- Instead of incrementing a variable, use a Date object, containing the time at the beginning, and compare it with the current time when the function is executed.
var beginTime = (new Date()).getTime();
var intervalId = setInterval(function() {
var timePassed = (new Date()).getTime() - beginTime;
document.getElementById('Submit').value = timePassed;
if(timePassed >= 4000) {
clearInterval(intervalId);
}
}, 30);

Milliseconds out of sync

I am developing a stopwatch application using Javascript/jQuery. The problem is that the milliseconds value is out of sync with REAL milliseconds. I am using function setInterval() with the interval of 1 millisecond, still it is causing this problem.
jsFiddle: http://jsfiddle.net/FLv3s/
Please help!
Use setInterval to trigger updates, but use the system time (via new Date()) for the actual time calculations.
To be honest, I tried nearly the same thing as you do now (Creating an accurate Metronome in Javascript only) - to make a long story short: To be absolutely accurate in terms of milliseconds (or lower) is sadly not (yet) possible with javascript only.
For more insight i recommend this question: Does JavaScript provide a high resolution timer?
or to be more precise this blog article: http://ejohn.org/blog/how-javascript-timers-work/
Best regards,
Dominik
Program execution in any language, not just JavaScript, is not realtime. It will take a tiny amount of time to actually run the code to increment your counter and update the view, and that throws the "timing" off.
Additionally, many browsers have a "minimum timeout" length, which varies between 4 and about 16 (the latter being the computer's own clock timer), which will really mess with your code.
Instead, you should use delta timing.
var startTime = new Date().getTime();
setInterval(function() {
var elapsed = new Date().getTime()-startTime;
// update view according to elapsed time
},25);
If you're worried about it looking choppy, consider using requestAnimationFrame instead, to update the timer exactly once per frame - this has the added benefit of not updating when the user switches tabs (but it will still be timing them) because if the tab is not active then there's no need to redraw stuff.
You can use the new performance object to get a more accurate time. Combine this with requestAnimationFrame instead of setInterval:
var startTime = performance.now(),
currentTime,
isRunning = true;
loop();
function loop(timeElapsed) {
currentTime = performance.now();
if (isRunning) requestAnimationFrame(loop);
}
Just subtract startTime from currentTime.
I left timeElapsed which contains time elapsed handed by rAF which you can may use also for something (or just ignore it).
One note though: not all browsers support this yet (and some may use prefix) so for mobile you need to use the standard system time object.

javascript setInterval

a question. If i use setInterval in this manner:
setInterval('doSome();',60000);
am i safe that the doSome() function is triggered every 60 seconds, even if I change the tab in a browser?
Passing a string to setInterval is fine, and is one of two ways to use setInterval, the other is passing a function pointer. It is not wrong in any way like the other answers state, but it is not as efficient (as the code must be reparsed) nor is it necessary for your purpose. Both
setInterval('doSome();', 60000); // this runs doSome from the global scope
// in the global scope
and
setInterval(doSome, 60000); // this runs doSome from the local scope
// in the global scope
are correct, though they have a slightly different meaning. If doSome is local to some non-global scope, calling the latter from within the same scope will run the local doSome at 60000ms intervals. Calling the former code will always look for doSome in the global scope, and will fail if there is no doSome function in the global scope.
The function will reliably be triggered, regardless of tab focus, at intervals of at least 60000ms, but usually slightly more due to overheads and delays.
All browsers clamp the interval value to at least a certain value to avoid intervals being too frequent (I think it's a minimum of 10ms or 4ms or something, I can't exactly remember).
Note that some browsers (the upcoming Firefox 5 is one, but there are probably others that I don't know of) further clamp setInterval drastically to e.g. 1000ms if the tab is not focused. (Reference)
No, the interval cannot execute until the event loop is cleared, so if you do for instance setInterval(func, 1000); for(;;) then the interval will never run. If other browsers tabs run in the same thread (as they do everywhere(?) except for in chrome, then the same applies if those tabs clog the event loop.)
But for an interval as large as 60000 it is at least very likely that the func will be called in reasonable time. But no guarantees.
If the tab with the setInterval() function remains open, then yes the function will be executed every 60 seconds, even if you switch to or open other tabs.
Yeah it works on an example I just created.
http://jsfiddle.net/5BAkx/
Yes, the browser's focus is irrelevant.
However, you should not use a string argument to setInterval. Use a reference to the function instead:
setInterval(doSome, 60000);
No, you are not guaranteed exact time safety. JS is event based (and single-threeaded) so the event won't fire at the exact right moment, especially not if you have other code running at the same time on your page.
The event will fire in the neighbourhood of the set time value, but not on the exact millisecond. The error may be tens of milliseconds even if no other event is running at the time. This may be an issue if for example you have a long-running process where the timing is important. If you do, you'll need to synchronize with a clock once in a while.
Yes it will be called as long as the page is open, regardless the tab is switched or even the browser is minimized.
However make sure you pass the function not a string to setInterval
it should be >
setInterval(doSome, 60000)
About "exact time safety": The following code starts UpdateAll at intervals of RefreshInterval milliseconds, with adjustment each second so that one start occurs at each second at the start of the second. There will be a slight delay for the finite speed of the computer, but errors will not accumulate.
function StartAtEachSecond ()
{
var OneSecond = 1000; // milliseconds
var MinInteral = 50; // milliseconds, estimated safe interval
var StartTime = OneSecond - (new Date ()).getMilliseconds (); // Time until next second starts.
if (StartTime < MinInteral) StartTime += OneSecond
window.setTimeout (StartAtEachSecond, StartTime + MinInteral); // To set up the second after the next.
for (var Delay = 0.0; Delay < OneSecond - MinInteral; Delay += RefreshInterval)
{
window.setTimeout (UpdateAll, StartTime + Delay); // Runs during the next second.
}
}

Categories