JavaScript is single-threaded

Damien Katz is mocking on an ONJava.com article that tries to implement Mutual Exclution for JavaScript.

I must say that I didn't really know it for sure that JavaScript is ALWAYS single-threaded, and there are never two threaded running in parallel. It is good to know that.

PS

After a long time of not blogging it, I noticed when I came back that WordPress.com has put back the Import options, so I imported my old Blogger blog into here.

2 Responses to “JavaScript is single-threaded”

  1. Alexei Says:

    I know you are referring to the way JavaScript is executed at the VM level, but one thing I would like to mention is that there are well established ways of using the timer object (setTimeout, setInterval) to do pseudo-multithreading. You can effectively create multiple threads of executing code this way.

  2. splintor Says:

    Hi Alexei,
    I must say I’m honored to have you commenting in my blog.
    I do know of these “pseudo-multi-threading” techniques, as you call them. I think these techniques lead developers to believe JavaScript is actually multi-threaded.
    In addition, it is obvious that the browser itself is multi-threaded, as it is capable of doing other things while the JavaScript is running. However, since you can rely on JavaScript not to be “really multi-threaded”, you can be sure that while a function is executed, it can safely assume that a global variable value will not be changed during its run, even when another function that was set to run using setTimeout changes it.
    This is not an assumption you can take when you code for a “real multi-threaded” environment.
    This is what Damien is mocking about, and what I meant by “it’s good to know that”.

    BTW, one of the outcomes of JavaScript single-threadiness is that when you call location.replace(), the code after it will execute and the window will be reloaded only when the function exits, or, on IE, when you yield execution to the system using function like alert().
    This is something I just recently found out.

Leave a reply to Alexei Cancel reply