Home > OS >  What is the difference between call stack and task queue in javaScript(event-loop)?
What is the difference between call stack and task queue in javaScript(event-loop)?

Time:11-03

I am confuse in differentiating between call stack and task queue in the context of event loop.

  • Call stack -->Every time a script or function calls a function, it's added to the top of the call stack.

  • Task queue---> A task is any JavaScript code which is scheduled to be run by the standard mechanisms such as initially starting to run a program, an event callback being run, or an interval or timeout being fired.

CodePudding user response:

The short answer is that the "Call Stack" is a built-in component of the JavaScript runtime and the Task/Event Queue is a component of the client application that contains the JavaScript runtime.

For example,

All browsers include a JavaScript runtime, which you can think of as an application written inside of the larger browser application. The call stack is a list of instructions that are to be called and this is part of the JavaScript runtime. So, if you have a function that calls another function, the call stack includes references to those functions that are being called. The JavaScript runtime is a single-threaded environment - - only one function can be executing at any given time.

Now, your browser is a multi-threaded environment - - the browser can be executing some JavaScript within the JavaScript runtime while it also is playing a video, for example.

When JavaScript requires an asynchronous operation (an operation that runs concurrent to some JavaScript running), the JavaScript runtime can "ask" the client application to place a reference to that function on the task (event) queue. When the JavaScript call task is empty (and no JavaScript operations are happening), the client's event queue is looked at and whatever is the next thing in that queue will be executed by the JavaScript runtime.

CodePudding user response:

Let me try to explain :)

JavaScript is an synchronous programming language. Event loop allows you make your solution async via browser API (callbacks, events and so on..)

So, your synchronous code is running in the stack: all function calls, all requests are initiated from here.

With ES6 (ECMAScript standard) you can use Promise, which callbacks are located in microtask queue.

Macrotask queue includes callbacks for setTimeout, setInterval, api requests and other.

Each event loop iteration represents sequential steps:

  1. First of all, JS executes all code in stack.
  2. Secondly, JS checks is any completed promise in microtask and runs it if exists.
  3. Lasts, JS checks and runs completed callbacks from macrotask queue.

FYI, you can lock UI if you incorrectly write your async block with Promise.

Hope, you find this useful!

  • Related