Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Javascript SetTimeout() is not multithreaded

Tags:

javascript

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

like image 573
zb' Avatar asked Aug 29 '12 22:08

zb'


People also ask

Why is JavaScript not multithreaded?

JS in browsers doesn't support multithreading in the event loop as it is not needed for 99.999% of the websites. The event loop handles everything seamlessly. For the remaining apps, devs can use web workers. Web Workers are a simple means for web content to run scripts in background threads.

Does setTimeout run on different thread?

This tells me that setTimeout() does not run on a separate thread. Show activity on this post. When you call setTimeout() typically control is passing back into the host environment (the browser or native node. js code for example).

Does setTimeout block thread?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.

Will JavaScript ever be multithreaded?

Thanks to recent advancements in the language--such as the Atomics and SharedArrayBuffers objects and Web Workers in the browser--JavaScript is now a multi-threaded language.


1 Answers

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.

like image 185
DVK Avatar answered Sep 19 '22 03:09

DVK