For the onload 2 functions below which are scheduled to be called 'onload' of these 2 images, what guarantees that one will completely finish before the other begins? Is there a queue behind the scenes of callbacks that need to fire in this single threaded environment?
if entryFunction never stops looping, does it pause its thread and yield to one of the doWorks()?
I've heard that javascript is not multithreaded, so is the entryFunction() yielding/pausing to these asynchronous function calls?
function entryFunction() {
var obj = new Image();
var obj2 = new Image();
// ...
obj.onload = function() { dowork(); }
obj2.onload = function() { dowork(); }
while (1) {
console.log("Actual work is being done");
}
}
function dowork() {
doThis();
doThat();
}
Both correct answers above me (that raw JS is single threaded and will block on that while). That said, there is a new HTML5 API called Web Workers that will give you concurrency in JS.
http://www.html5rocks.com/en/tutorials/workers/basics/
They are 'true' (in so far as the developer is concerned) concurrency. Some browsers do implement them as true concurrency, some fudge it with behind the scenes coroutines and schedulers.
Javascript is not multithreaded but it is event-driven.
dowork()
will be called unlessonload()
is called by something.Apart from that while(1) will not cause the code to go forward. Instead of
while(1)
usesetInterval
or setTimeout. That way function doesn't block rest of the code.Race condition is possible if
new Image()
causeonload()
to be called as onload is being set afternew Image()
Nothing guarantees it.
You're only guaranteed they won't run at the same time.
The while loop will block other js from running.
The browser itself isn't limited to a single thread implementation. Javascript itself runs in a single run loop, but that doesn't guarantee the remainder of the things in the browser do (and they don't).
Your code will not ever leave the
while
loop. Because JavaScript only has one thread, you mustreturn
from every function to return control back to the environment.In your example, your example will cause your browser to set up and download images in separate threads (since the browser is multithreaded). When the images are downloaded, the environment will queue up calls to
onload()
. These would run the next time your JavaScript program returns control back to the environment.But since you are holding control indefinitely in your
while
loop, control never returns to the environment, and the queued-up events will never run.