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 :)
Related
I'm a NodeJs developer that happens to have some web applications.
I'm very familiar with asynchronous code and how the event loop works. However I been facing a problem that I was unable to fix until I realized that asynchronous code may behave different when it is splitted across several script tags.
The situation was as follows
I had one script tag at the head section with some asynchronous code. Such code expected some function to exist. That function should be declared on the second script tag in a synchronous fashion, so at the time the async stuff completes that function should exist.
Te second script tag is 100% synchronous and at the middle of the code it created a function called boot.
Let me ilustrate it with some simplified code:
// <script>
somePromise()
.then( ()=> window.boot())
// </script>
// < ... some html code and body >
// <script>
window.boot = function (){}
// </script>
Since the promise callback should be executed asynchronously I expected it to go to the event loop and allow the rest of the synchronous code to execute.
On some browsers, this worked as I expect. When I say some browsers I mean browsers of different users on different computers, because the behavior varies even using the same browser brand and version. However, there were situations when the promise callback was executed before the second second script tag had a chance to start and raising an error.
How is this supposed to work on browsers ? Is each script tag executed until all its code is executed, even the asynchronous one ? If that is the case, why does it work for some other browsers?
Thanks in advance.
The HTML5 parser is not synchronous.
This is my own reworded extract of parts of HTML Parser Threading on MDN. Please refer to the original for formal treatment and heavy reading.
HTML between the script tag [pairs] is parsed by a nsHtml5StreamParser which executes off the main thread.
The parser runs its own event loop, and responds to requests from the main thread to perform onDataAvailable and OnStopRequest processing. Processing calls DoDataAvailable and doStopRequst respectively.
DoDataAvailable outputs small DOM tree operations, such as element creation into a queue processed in the main thread. The tree op queue is flushed to the main thread from time to time ** using a timer.**
After flushing the parser dispatches a runnable to the main thread to process tree additions. The runner (or executor) in the main thread calls nsHtml5TreeOpExecutor::RunFlushLoop().
A comment from #KarelG in this question says that network data is usually processed in 8Kb chunks. The question is well worth reading.
So the JavaScript Event Loop sometimes gets an opportunity to fulfill a promise and execute an onFulfilled handler before the second script element is parsed and executed - as you already discovered!
In summary it apppear that the vagaries of network retrieval of source code, asynchronous HTML parsing that uses a timer to instigate processing of tree building operations, and any further asynchronous operations that the tree builder may or may not invoke, all combine together to create a race condition.
The unpredictability of the failure branch of the race condition, when window.boot is not defined when called, is most likely due to the combined effects of browser brand, network speed, device utilization, length and type of HTML content, and HTML parser timing and timers.
The obvious conclusion is that code should not set up this kind of race condition in the first place. It is unsafe coding practice. Thankfully you can work around it.
Actually, promise is not suported in IE, so what you could do is to use some external libs, like bluebirdJS, or you could use a transpiler (babel or another one)
If you use plain script tags on an HTML page, rendering is blocked until the script has been downloaded and parsed. To avoid that, for faster page display, you can add the 'async' attribute, which tells the browser to continue processing down the page without waiting for that script. However, that inherently means that other javascript that refers to anything in that script will probably crash, because the objects it requires don't exist yet.
As far as I know, there's no allScriptsLoaded event you can tie into, so I'm looking for ways to simulate one.
I'm aware of the following strategies to defer running other code until an async script is available:
For a single script, use their 'onload' event or attribute. However, there's no built-in way I know of to tell when ALL scripts have loaded if there's more than one.
Run all dependent code in onload event handlers attached to the window. However, those wait for all images too, not just all scripts, so the run later than would be ideal.
Use a loader library to load all scripts; those typically provide for a callback to run when everything has loaded. Downside (besides needing a library to do this, which has to load early), is that all code has to wrapped in a (typically anonymous) function that you pass into the loader library. That's as opposed to just creating a function that runs when my mythical allScriptsLoaded fires.
Am I missing something, or is that the state of the art?
The best you could hope for would be to know if there are any outstanding async calls (XMLHttpRequest, setTimeout, setInterval, SetImmediate, process.nextTick, Promise), and wait for there to not be one. However, that is an implementation detail that is lost to the underlying native code--javascript only has its own event loop, and async calls are passed off to the native code, if I understand it correctly. On top of that, you don't have access to the event loop. You can only insert, you can't read or control flow (unless you're in io.js and feeling frisky).
The way to simulate one would be to track your script calls yourself, and call after all script are complete. (i.e., track every time you insert a relevant script into the event loop.)
But yeah, the DOM doesn't provide a NoAsyncPending global or something, which is what you'd really require.
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.
I'm currently experimenting with embedding V8 in a project of mine. Since I use libev for listening to sockets and events and want to be able to script events with JS I would want to be able to just run v8 for a short while and then jump back to C++ to check for events and such and then go back to running JS-code. Since I haven't done much script embedding earlier I'm sure there are some clever way that this usually is done in so all ideas are appreciated.
The cleanest way I found of doing this is to create setTimeout and clearTimeout functions within JS. setTimeout creates a ev::Timer which has a callback that gets called after a certain amount of time. This makes it so that when you call a JS function you continue to execute that until it returns, but that function can set a number of timeouts which aren't called until after you exit the current JS and there hasn't happened any other libev events during the execution, in that case those are handled first (in C++). The limitations of this method is that the coder who writes JS has to remember to not write functions that goes into eternal while-loops or similar. A loop is instead done like this:
function repeat() { setTimeout(repeat, 0); }
In javascript, is there any different between these two:
// call MyFunction normal way
MyFunction();
// call MyFunction with setTimeout to 0 //
window.setTimeout('MyFunction()', 0);
The reason I asked was because recently came across the situation where the code only works if I use setTimeout(0) to call the function.
To my understanding, setTimeout(0) is exactly same as calling a function directly because you dont set any delay. But from what I see how it works in the code, setTimeout(0) seems to get executed last.
Can someone clarify exactly how setTimeout(0) really get called in order of the rest of other function call?
setTimeout() always causes the block of JavaScript to be queued for execution. It is a matter of when it will be executed, which is decided by the delay provided.
Calling setTimeout() with a delay of 0, will result in the JavaScript interpreter realizing that it is currently busy (executing the current function), and the interpreter will schedule the script block to be executed once the current call stack is empty (unless there are other script blocks that are also queued up).
It could take a long time for the call stack to become empty, which is why you are seeing a delay in execution. This is primarily due to the single-threaded nature of JavaScript in a single window context.
For the sake of completeness, MyFunction() will immediately execute the function. There will be no queuing involved.
PS: John Resig has some useful notes on how the JavaScript timing mechanism works.
PPS: The reason why your code "seems to work" only when you use setTimeout(fn(),0), is because browsers could update the DOM only when the current call stack is complete. Therefore, the next JavaScript block would recognize the DOM changes, which is quite possible in your case. A setTimeout() callback always creates a new call stack.
I would guess that the timeout only starts when the page is fully loaded, whereas just a plain 'MyFunction()' will execute as soon as it's processed.
The timer will try to execute once your current thread is done. This depends on where you call the window.setTimeout(). If it is in a javascript tag, but not inside a function, then it will be called once the end of the javascript tag is reached. For example:
<html>
<script type="text/javascript">
setTimeout(function(){alert("hello")},0);
var d=Number(new Date())+1000;
while(Number(new Date())<d){
}
alert("hi");
</script>
</html>
If you call the setTimeout inside a function that results from an event occuring, for example onload, then it will wait until the event handler function returns:
<html>
<script type="text/javascript">
document.addEventListener("mousedown",function(){
setTimeout(function(){alert("hello")},0);
var d=Number(new Date())+1000;
while(Number(new Date())<d){
}
alert("hi");
}, true);
</script>
</html>
It is impossible to make one thread in JavaScript wait while another thread is running. Event listeners will wait until the current thread is done before they start running.
The only exception is Web Workers, but they run in a different file, and the only way to communicate between them is using event listeners, so while you can send a message while the other is working, it won't receive that message until it is done, or it manually checks for messages.