anon
anon

Reputation:

why Javascript SetTimeout() is not multithreaded

I have a test:

Html:

<div id="f1">Empty</div>
<div id="f2">Empty</div>

​

js:

var s1 = function() {
    for (i = 1; i < 1000000000; i++) {
        var b = i * i;
    }
    $('#f1').html('Set');
}

var s2 = function() {
    if ($('#f1').html() == 'Empty') {
        $('#f2').html('Multi Thread');
        return;            
    };
    $('#f2').html('One Thread');
}

setTimeout(s2,110);
setTimeout(s1,100);​

is there any real reason why setTimeOut() not run in different threads, instead like event model ?

jsfiddle

Upvotes: 12

Views: 13518

Answers (8)

Anand A.S
Anand A.S

Reputation: 107

After waiting for the given amount of time, The execution for the methods (s1, s2) still happen in the javascript thread itself (which is single threaded).

The reason why s2 waits for s1.

Upvotes: -1

LetterEh
LetterEh

Reputation: 26696

eicto, setTimeout doesn't fire code when requested.
It queues code, inline, with ALL of the other code that comes before it, but it sets its place in line to be at minimum the time requested.

Moreover, most browsers have hard limits for minimum timeouts.
If you request a 1ms timeout, chances are good that in most browsers, you're going to get your request back 10ms-15ms later.

All of the JS interaction with the DOM, and, in reality, pretty much everything a single page does, all happens on one thread, with certain exceptions for custom browser extensions, and a few new APIs (like webworkers).

This is why large projects need to be considerate of everything else on the page, and why everything needs to be asynchronous.

Because setTimeout isn't a sleep and it doesn't return on the exact microsecond that it was croned in for... ...it puts a callback on the event stack, for a time no earlier than what you specify.

Upvotes: 4

einpoklum
einpoklum

Reputation: 131525

Mozilla does support multi-threading in Javascript - as long as you don't want to do UI work from multiple threads. The early versions of my Remove Duplicate Messages (Alternatve) exentsion were multi-threaded.

See my own bug page regarding this issue in my extension, or better still, this page about using worker threads in Mozilla. eicto, you could very well implement your code using a background thread.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707288

Lots and lots of design decisions went into Javascript's implementation in a browser that assumed it had only single thread access to the browser DOM and to other global variables/properties. This makes programming with it a lot less likely to cause problems, but introduces some limitations that have to be dealt with.

The language itself is perfectly capable of being multi-threaded and we already see that in WebWorkers and in some server implementations of the language. But, any time you use multiple threads and try to read/write to variables or properties that are shared between multiple threads, one MUST use protective devices (like mutexes) to allow reliable access to those shared resources. That significantly complicates how to do this programming and Javascript in a browser decided NOT to require that level of understanding in order to program it reliably.

For anyone who has done multi-threaded programming, it can be powerful, but it is very, very easy to introduce difficult to find bugs. Those who are responsible for Javascript in a browser decided that that level of difficulty and the resulting types of bugs should be avoided entirely.

Even now with WebWorkers, there are no shared resources between a WebWorker and the main javascript thread. The two must communicate via a message passing system which is a foolproof way of forcing safety. And, the consequence is that one cannot access the DOM from a WebWorker. Instead, if you want the DOM to be changed, you have to post a message to the single main thread and ask IT to update the DOM. The main thread will recieve that message only when it's done doing other things (it's single threaded).

It is also likely that the DOM has now spent a zillion years as a structure that is only designed for single threaded access so it would be a gigantic task to design and implement a way to access it from multiple threads (and fix all the resuling bugs in that implementation).

Upvotes: 4

austincheney
austincheney

Reputation: 1199

JavaScript is not multithreaded, but even if it were setTimeout is a synchronous. setTimeout and setInterval are supplied by browsers outside of the proper JavaScript language, which provides an external means of access to the language, like event execution. When people refer to JavaScript as an asynchronous or multithreaded language this is likely what they are referring to because multiple external access points, such as numerous timers or event executions, can occur simultaneously each spawning a unique access point to the interpreter in memory. This is exactly what the developers of Node.js are referring to when they make such claims about JavaScript.

This means of multiple external access to various isolated threads can cause collisions in the UI, because a simulated multithreaded effect will likely cause collisions in browser output where there is only a single document object representing the entirety of a page. This is why setInterval with a short interval is generally deemed unsafe. setInterval is entirely asynchronous and will execute according to the interval provided even if execution in the prior interval has not concluded. This kind of collision is what I call fallover because the next interval is executing code that is falling over the prior execution and if your code requires access to the DOM or uses closures you will likely have problems. For safety a recursive setTimeout is recommended, because it is synchronous and the next round of execution will not occur until the prior has completed.

Upvotes: 1

DVK
DVK

Reputation: 129403

Javascript is not multithreaded nor non-multithreaded per se. However, the specific implementations of Javascript that currently are implemented in major browsers mostly ARE single-threaded.

In addition, for proper multithreading, the language needs to have facilities for shared memory, locks, semaphors and other concurrent programming tools, which JavaScript as is currently defined does not have (for example, there is no way to describe how concurrent JS threads would control who gets to update DOM objects that are of course, shared since there's only one DOM in a window).

There are attempts to make JS more parallelized - look at web workers, Intel's River Trail, Google's HTML5 work and more.

Upvotes: 17

Richard Heath
Richard Heath

Reputation: 347

Javascript is not multi threaded.

HTML5 will give javascript multithread capabilities.

Upvotes: 0

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

Javascript don't support multithreading because the your interpreter in the browser is a single thread

Upvotes: 2

Related Questions