Skip to content
Advertisement

Is the event loop in Javascript executing in a separate thread?

I still believe Javascript is single threaded, but when I think about the event handling mechanism, I have some doubts.

  • Is event loop a separate thread, which pulls events one by one from queue and process.

Why I think like this is even while processing one event from queue, it can listen or it can push events to same queue. I created an example as below:

<html>
<head>
<script>
function clicked(){
    alert("clicked in between..");
}
function longRun(){
    for(var i=0;i<50000;i++){
        console.log(i);
    }
    alert("completed .... ");
}

</script>
</head>
<body>
    <input type="button" value="quick!" onclick="clicked();"/>
    <input type="button" value="long run!" onclick="longRun();"/>
</body>
</html>

When I click on long run! it will take some time to complete, but in the meanwhile if I click on quick! it will be added to the event queue and will be executed immediately after the long run event.

What is actually happening? Can anyone explain / correct me

Advertisement

Answer

Except for webWorkers (which we aren’t talking about here), there is only one “user thread” per window in a browser. That means there’s only one thread running your user Javascript.

This does not mean that the browser engine under the covers does not have some other threads to handle non-Javascript processing. In fact, this is very likely the case. But, since these other possible threads, never actually run any of your Javascript or affect any of your Javascript variables, they don’t directly affect the JS execution environment.

Yes, these other threads may indeed insert things into the JS event queue that will be picked up later when the main JS thread is ready to process the next event.

See this answer How does JavaScript handle AJAX responses in the background? for more info and a list of related articles.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement