A Reliable timer for Javascript - javascript

I have a web site and i am using a javscript timer to swap images about.
I am using the timer like this:
var myTimer = window.setTimeout(MyFunction, MyInterval);
function MyFunction
{
//do something
//recalll timer
}
Now, the problem I have is not that the interval does not fire off at regular intervals as I can accept that in my application and I understand why it can vary.
The issue I have is that every now and then the timer stops for a few seconds and then resumes.
What I am trying ascertain is what is the main cause of this random suspension of the timer?
Is it due to the resources being diverted to another process on the hosting browser PC OR is it just the nature of using a JavaScript timer?
If the latter should I look to do an eternal loop? Everywhere I read and have practised elsewhere indicates that an infinite loop will grab all the resources and it would be a greater evil than the timer random suspension.
Are there any alternatives to using a javascript timer when a regular quick execution of code is paramount?
Thanks

The code you run inside MyFunction takes some time to execute (depending on what you are doing). When you recall the timer at the end of that function, the interval is not exactly MyInterval, because of the code execution time being added.
If you use setInterval() instead of setTimeout(), the given function will be executed exactly every MyInterval milliseconds rather than (MyInterval + execution time) milliseconds.
To answer your question, the random suspension happens because of the execution time of your code.

I had a similar issue on a website I was working on and ultimately found the culprit in another timer-triggered job in a jQuery plugin that was occasionally delaying execution of my own function. If you're using external code in your site, you could do some debugging to see if this is your case too.
As a possible remedy, you could give a look at web workers. Since worker tasks are executed in a separated thread, they are not subject to delay when something in your main thread is taking too long to complete.
Your code would then look like this:
var worker = new Worker('worker.js');
And in another file called "worker.js" you would write:
var myTimer = setTimeout(MyFunction, MyInterval);
function MyFunction
{
//do something
//recalll timer
}
Just note that there is no window. anymore before setTimeout. This is because web workers don't have direct access to the DOM.
It's not guaranteed to solve your problem, but it's worth a test.

Related

Running setTimeout() or setInterval() asynchronously

Is it possible to execute setTimeout() or setInterval() synchronously so that further execution that depends on its callback will not cause a not defined error?
intv = window.setInterval(function() {
// do some stuff
doSomeStuff();
// kill interval when stuff is done
if (stuffIsDone)
window.clearInterval(intv);
}, 10);
// dependent on "stuff" being done
// I want this to execute only after intv is cleared
doMoreStuff();
I don't want to put every consecutive call inside of a timeout to check if (typeof someStuff != 'undefined')
Yes, I do understand that this will cause a delay in loading and possible the UI. The intervals will be extremely small and inconsequential.
EDIT... Alright, what I'm ultimately trying to do is dynamically add a number of javascript files dynamically, by only including a single javascript file.
ie.:
// auto include all javascript files
<script language="javascript" type="text/javascript" src="include.js"></script>
This works by requesting the JSON list of javascript files from the server via AJAX. It loops through the list and adds the scripts dynamically to the DOM.
The catch:
If I add the scripts using setInterval, they are sometimes added after the onLoad event fires, depending on the current computational load of the machine executing the code. So, when I call functions from one of the files onLoad, it causes an error (because at the time of execution, the function didn't exist)
If I add the scripts inside of a while loop, the dynamically added scripts to do not execute and the internal references between the scripts are invalid and error out.
So, the question really is: without using setInterval and typeof on every call, how do I dynamically add scripts reliably so that dependent code doesn't attempt to execute before the depended-upon scripts are loaded?
Take a look at Refactoring setInterval-based Polling and consider converting your setInterval to a setTimeout and use a Promise to execute doMoreStuff() after stuffIsDone is true.
That article is from 2013, so consider Promises/A+ (using a polyfill for ES6-style Promises for older browsers) instead of jQuery's or Underscore's implementation.
You can run a while loop and keep track of the system time if you want to block the JavaScript thread for a fixed period of time.
For example:
var startMillis = Date.now();
while (Date.now() - startMillis < 10);
Note that no other code will run during this period. JavaScript is single threaded.
Don't know exactly what you're trying to do, but this seems a little strange :)

Javascript internals - clearTimeout just before it fires

Let's say I do this:
var timer = setTimeout(function() {
console.log("will this happen?");
}, 5000);
And then after just less than 5 seconds, another callback (from a network event in NodeJS for example) fires and clears it:
clearTimeout(timer);
Is there any possibility that the callback from the setTimeout call is already in the queue to be executed at this point, and if so will the clearTimeout be in time to stop it?
To clarify, I am talking about a situation where the setTimeout time actually expires and the interpreter starts the process of executing it, but the other callback is currently running so the message is added to the queue. It seems like one of those race condition type things that would be easy to not account for.
Even though Node is single thread, the race condition the question describes is possible.
It can happen because timers are triggered by native code (in lib_uv).
On top of that, Node groups timers with the same timeout value. As a result, if you schedule two timers with the same timeout within the same ms, they will be added to the event queue at once.
But rest assured node internally solves that for you. Quoting code from node 0.12.0:
timer.js > clearTimeout
exports.clearTimeout = function(timer) {
if (timer && (timer[kOnTimeout] || timer._onTimeout)) {
timer[kOnTimeout] = timer._onTimeout = null;
// ...
}
}
On clearing a timeout, Node internally removes the reference to the callback function. So even if the race condition happens, it can do no harm, because those timers will be skipped:
listOnTimeout
if (!first._onTimeout) continue;
Node.js executes in a single thread.
So there cannot be any race conditions and you can reliably cancel the timeout before it triggers.
See also a related discussion (in browsers).
I am talking about a situation where the setTimeout time actually expires and the interpreter starts the process of executing it
Without having looked at Node.js internals, I don't think this is possible. Everything is single-threaded, so the interpreter cannot be "in the process" of doing anything while your code is running.
Your code has to return control before the timeout can be triggered. If you put an infinite loop in your code, the whole system hangs. This is all "cooperative multitasking".
This behavior is defined in the HTML Standard, the fired task starts with:
If the entry for handle in the list of active timers has been cleared, then abort these steps.
Therefore even if the task has been queued already, it'll be aborted.
Whether this applies to Node.js, however, is debatable, as the documentation just states:
The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.

Questions related to JavaScript setInterval

I have two questions related to the JavaScript's setInterval() method.
I haven't found any practical cases (but I guess it's not impossible also) related to these question, but for curiosity I wanted to ask these questions.
1.) What happens if the code to be be executed by the setInterval() takes more time than the time interval provided? Does the previous execution stops and the current one starts executing or both will run in parallel.
2.) What if the whole system (OS) is hanged between the time gap when setInterval() is called? Is it possible that the code can execute with some different interval during this condition? I mean does setInterval() guarantees that the code will be executed at the specified interval only?
Thanks
JavaScript uses single threaded execution. Functions such as setTimeout and setInterval lead many to believe that it is possible to multi-thread in JavaScript. In reality, setInterval and setTimeout merely schedule a function or expression to execute at a specified time and those functions are added to the same single-threaded stack. If the browser is in the middle of processing something else when a setTimeout or setInterval is scheduled to fire, the scheduled functions will execute as soon as the browser can get to it.
setInterval does not guarantee that a function will execute at the specified interval only. setInterval will try to execute a function at the specified time, but any number of things could delay the execution or prevent it from executing altogether.
Quoting this article by John Resing:
If a timer is blocked from immediately executing it will be delayed until the next possible point of execution (which will be longer than the desired delay).
Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).

Can JavaScript's setInterval block thread execution?

Can setInterval result in other scripts in the page blocking?
I'm working on a project to convert a Gmail related bookmarklet into a Google Chrome extension. The bookmarklet uses the gmail greasemonkey API to interact with the gmail page. The JavaScript object for the API is one of the last parts of the Gmail page to load and is loaded into the page via XMLHttpRequest. Since I need access to this object, and global JavaScript variables are hidden from extension content scripts, I inject a script into the gmail page that polls for the variable's definition and then accesses it. I'm doing the polling using the setInterval function. This works about 80% of the time. The rest of the time the polling function keeps polling until reaching a limit I set and the greasemonkey API object is never defined in the page.
Injected script sample:
var attemptCount = 0;
var attemptLoad = function(callback) {
if (typeof(gmonkey) != "undefined"){
clearInterval(intervalId); // unregister this function for interval execution.
gmonkey.load('1.0', function (gmail) {
self.gmail = gmail;
if (callback) { callback(); }
});
}
else {
attemptCount ++;
console.log("Gmonkey not yet loaded: " + attemptCount );
if (attemptCount > 30) {
console.log("Could not fing Gmonkey in the gmail page after thirty seconds. Aborting");
clearInterval(intervalId); // unregister this function for interval execution.
};
}
};
var intervalId = setInterval(function(){attemptLoad(callback);}, 1000);
Javascript is single threaded (except for web workers which we aren't talking about here). That means that as long as the regular javascript thread of execution is running, your setInterval() timer will not run until the regular javascript thread of execution is done.
Likewise, if your setInterval() handler is executing, no other javascript event handlers will fire until your setInterval() handler finishes executing it's current invocation.
So, as long as your setInterval() handler doesn't get stuck and run forever, it won't block other things from eventually running. It might delay them slightly, but they will still run as soon as the current setInterval() thread finishes.
Internally, the javascript engine uses a queue. When something wants to run (like an event handler or a setInterval() callback) and something is already running, it inserts an event into the queue. When the current javascript thread finishes execution, the JS engine checks the event queue and if there's something there, it picks the oldest event there and calls its event handler.
Here are a few other references on how the Javascript event system works:
How does JavaScript handle AJAX responses in the background?
Are calls to Javascript methods thread-safe or synchronized?
Do I need to be concerned with race conditions with asynchronous Javascript?
setInterval and setTimeout are "polite", in that they don't fire when you think they would -- they fire any time the thread is clear, after the point you specify.
As such, the act of scheduling something won't stop something else from running -- it just sets itself to run at the end of the current queue, or at the end of the specified time (whichever is longer).
Two important caveats:
The first would be that setTimeout/setInterval have browser-specific minimums. Frequently, they're around 15ms. So if you request something every 1ms, the browser will actually schedule them to be every browser_min_ms (not a real variable) apart.
The second is that with setInterval, if the script in the callback takes LONGER than the interval, you can run into a trainwreck where the browser will keep queuing up a backlog of intervals.
function doExpensiveOperation () {
var i = 0, l = 20000000;
for (; i < l; i++) {
doDOMStuffTheWrongWay(i);
}
}
setInterval(doExpensiveOperation, 10);
BadTimes+=1;
But for your code specifically, there's nothing inherently wrong with what you're doing.
Like I said, setInterval won't abort anything else from happening, it'll just inject itself into the next available slot.
I would probably recommend that you use setTimeout, for general-purpose stuff, but you're still doing a good job of keeping tabs of the interval and keeping it spaced out.
There may be something else going on, elsewhere in the code -- either in Google's delivery, or in your collection.

setInterval() behaviour with 0 milliseconds in JavaScript

In my application I found some JavaScript code that is using setInterval with 0 milliseconds, like so:
self.setInterval("myFunction()",0);
Obviously, this does not seem like a good idea to me. Can anyone tell me what will be the behaviour of setInterval here? ("myFunction" makes an AJAX call to the server)
I am asking this because I am having an irregular behaviour in my application. 90% of the times, the application behaves correctly and exactly one call to the server is made. However sometimes, multiple calls are made to the server (until now, maximum is 48 calls) and I am almost certain it is the fault of this line of code.
Browser set a minimal value for the interval. Usualy 10ms, but it can depend on the browser. This means repeat this as fast as I'm possibly allowed. The W3C spec say 4ms : http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers
This is correct but probably reveal a design error.
EDIT: By the way, it is bad practice to pass a string to setTimeout/setInterval, pass a function instead as javascript has first class functions.
setInterval(myFunction, 0) calls myFunction continuously with minimum delay. It is almost like calling myFunction in a infinite loop. Except that here you can stop the loop using the clearInterval method.
To have it executed only once with minor delay, use setTimeOut instead:
window.setTimeout(myFunction, 10);
As you're using AJAX, you don't have to use any timers at all - just call the next AJAX request in the Callback (complete/success event) of the current AJAX request.
Post your current code and we might be able to guide you further.
I assume that in myFunction() there is a clearInterval.
Basically, you've set an interval that can happen as often as possible. If the browser executing JavaScript actually gets to the clearInterval part before the next iteration of the interval, then it will be fine. Otherwise, it will happen again and again.
Use setTimeout instead.
setInterval with '0' moves the code execution at the end of the current thread. The code is put to the side, all other code in the thread is executed, and when there is no code for execution, then the side code is executed.

Categories