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
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With