How is JavaScript running in browser able to Listen to on scroll event along with ajax responses at the same time?

Viewed 51

I have a basic question related to JavaScript.

The scenario is a user scrolling down a news feed of some social media app.

This would have three different processes occurring in-between each other.

  1. on scroll event
  2. creating ajax request to some URL
  3. receiving responses to these requests.

There can be any relative order of these once the first request is fired.

So my question being is there two different processes running at the same time?

  • one to listen to on-scroll events.
  • one to listen to the received response.

If so how is it synchronized on the event loop and how does the process run (given the single-threaded nature of js and possible single-core environment)?

Are these processes spanned by the browser? If so how is the synchronism maintained between event loop, browser stack, execution stack, and these processes?

1 Answers

JavaScript is single threaded but the browser isn't.

By saying that a JavaSript is single threaded we mean that there's only one sequence of instructions currently executing at a given time (on the main thread, you can now have worker threads running in parallel to main thread similar to the situation when you have two browser tabs open).

JavaScript engine (in chrome it's V8) is part of the browser and it executes JavaScript code according to the ECMAScript specification.

In the browser there are built in APIs added to JavaScript so it might seem that they are part of the JS itself but they're not.

DOM is a browser API. When you use any functionality related to the DOM, JavaScript gets out of its "world" and communicates with external services.

It's not JavaScript engine that renders and changes the page. When you use DOM API you aren't changing the document directly - you're just telling the browser renderer what changes needs to be done. Even the event loop is not a part of V8 - it's a browser construct.

Events are picked up by the browser and when there's some listener associated with a particular event then the handler is added to event loop (which is just a queue with things to do). When there's some job in the queue it's performed by V8 and when it completes the next job is taken care of.

Related