0

Javascript is one-threaded, that means one thing happens at the time and there's a queue of events that get input and then executed, perhaps it looks like this:

click > mouseMove > functionA > functionB

But there's the confusion: does a function run stop for a few micro-seconds so that my mouseMove event is handled? How can I run a big function that takes a while to finish and still click items?

Assuming I was running on a very, very slow computer, in theory, would I have to wait for a console.log for my mouseMove to register and do its thing?

coolpasta
  • 725
  • 5
  • 19
  • the code you write is executed in a "single threaded" manner ... however, there is a thing called an [event loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop) and most of the operations in, for instance xmlhttprequest don't run in this eventloop - they probably run in a separate execution thread totally unrelated to javascript – Jaromanda X Sep 20 '19 at 02:46
  • Events and timers are handled by the _event loop_. _“Assuming I was running on a very, very slow computer, in theory, would I have to wait for a `console.log` for my `mouseMove` to register and do its thing?”_ — probably depends on the JS engine. Some operations actually stop and let some events finish midway, e.g. [BigInt multiplication](https://chromium.googlesource.com/v8/v8/+/master/src/objects/bigint.cc#520) (kinda… maybe only interrupt signals). – Sebastian Simon Sep 20 '19 at 02:47
  • 1
    if your code is `while(true);` - in most browsers, (before they offer to kill such code) no events in your code will be processed until that loop is stopped – Jaromanda X Sep 20 '19 at 02:48
  • You don't need a very very slow computer to test-run your use-case just run the script `while(true) console.log(new Date())` on your `powerful computer` from your browser console and see what happens. – Giddy Naya Sep 20 '19 at 02:53
  • Possible duplicate of [How to avoid freezing the browser when doing long-running computations in Javascript](https://stackoverflow.com/questions/13546493/how-to-avoid-freezing-the-browser-when-doing-long-running-computations-in-javasc) – Giddy Naya Sep 20 '19 at 03:02

0 Answers0