简体   繁体   中英

Why does javascript's forever loop blocks the page?

Why does typing anything on input#q hangs the entire page?

<html>
<head></head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="q">
<input>
<script type="text/javascript">
$("#q").keydown(function() {
    while(true) {
    }
});
</script>
</body>
</html>

http://jsfiddle.net/9cw2pjym/

The behavior I would expect is that the thread handling that particular keydown event would block, but the page would remain responsive. I did the test because I was curious to know if that code would prevent the user from typing on input#q. However, it goes far beyond that: the whole page blocks (I tried it on Chrome, Firefox and Safari).

I went ahead and tried this:

setTimeout(function() {
    while(true){}
}, 5000);

after 5 seconds the page hangs. No more interactions are possible. Shouldn't that be on a different thread as well? Is javascript and all other interactions with the page running on the same thread?

javascript is single threaded. So, even though setTimeout starts a timer, the callback event is invoked on UI thread only. That's the reason after 5 seconds your while(true){} forever loop hangs the UI thread.

Basically most user-interfaces and specifically web-browsers are single threaded. They give an apparency of multithreading by a fairly complex event model. But it will only do one thing at once.

However, since HTML5 this is not quite correct anymore, it offers support for running multi threaded using WebWorkers for background computations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM