Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...