10

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tom Sebastian
  • 3,373
  • 5
  • 29
  • 54
  • _“I still believe javascript is single threaded.”_ Take a look at [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers). – Sebastian Simon Aug 12 '15 at 04:31
  • Ok I got it. but my doubt is different – Tom Sebastian Aug 12 '15 at 04:36
  • 1
    This was a great question, I actually ended up at this Q&A because I googled the nearly the same question, however; I don't find any answers here satisfactory. It has been a while since you posted this, if you have a more satisfactory answer I suggest answering this your self, as it could help people who think like you do. – JΛYDΞV May 02 '21 at 06:43

4 Answers4

7

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.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • this makes sense. Can you have any resources explaining the" these other threads may indeed insert things into the JS event queue" . Will be helpful – Tom Sebastian Aug 12 '15 at 04:40
  • @TomSebastian - did you read the other answer I linked and the articles it references? There's lots of info in those. All operations that have async callbacks (timers, Ajax calls, etc...) need to be able to insert items in the queue while the main JS thread is currently executing. It is possible to do this pre-emptively during the JS execution thread (since the interpreter could look for other activity to respond to between JS execution steps), but it is more likely that additional threads are used to respond to these other activities. Which way it actually works is up to the implementation. – jfriend00 Aug 12 '15 at 04:41
2

There is only one thread per tab. This thread does both JavaScript execution and screen updates. While longRun is executing, you cannot react to a click on a button; the event you registered will be fired after all 50000 iterations are complete.

To clarify: events get put on a queue. The queue is getting executed in order by the tab thread.

EDIT: And, indeed, there's workers, but they act as if they were executing in a different tab - they have their own context, and can only communicate with the invoking program using postMessage.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • 1
    Here's a great article explaining the JavaScript event loop (and Web Workers)! http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/ – Jack Guy Aug 12 '15 at 04:33
  • I agree, but before completing 50000 iterations , when i click on the quick button the event is added to the queue, that means it is parallel ? – Tom Sebastian Aug 12 '15 at 04:35
  • 1
    What is parallel? Accepting a button click on a screen element is not JavaScript's responsibility. I am not 100% sure of the details as I'm a high-level guy, but basically the window manager / kernel delivers the click to the browser, the browser puts it into the JavaScript event queue. No JavaScript has yet been run. – Amadan Aug 12 '15 at 04:37
0

every browser use stack if you use safari so you will see in inspect element that the operation are putted in a stack so according to your script code first it goes to complete the loop of 5000 iteration.

  • Function invocations are stacked. Events are queued. – Amadan Aug 12 '15 at 04:38
  • hi Amadan Actually this is bit confusing if you use two function like that test(); test1(); as first one get call not complete working it also start second one also. – Sumit Aswal Aug 12 '15 at 05:37
  • This example shows you the function invocation stack: `function test() { test1(); }; function test1() { console.log(new Error().stack); } test()`. But events do not use the stack. – Amadan Aug 12 '15 at 06:01
-1

Javascript works on single thread.Event are queued and processed in fifo order.

What we are doing is writing event handler that is nothing but callback function that will be executed once event is processed from queue so its single threaded but asynchronous in nature.

You can learn more about it from http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/

Juned Lanja
  • 1,466
  • 10
  • 21