Search code examples
javascriptcallstackevent-looptask-queue

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


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.


Solution

  • 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!