JavaScript Event Loop – Webkul Blog

Agenda:

  1. JavaScript Introduction
  2. Call Stack Introduction
  3. Asynchronous Callback
  4. Task Queue
  5. Event Loop

1 JavaScript introduction

  • JavaScript is a single threaded, non-blocking, asynchronous concurrent language.
  • It has a call stack, an event loop and a callback queue + other APIs.
  • V8 is the JavaScript engine which has a call stack and a heap.
  • The heap is used for memory allocation and the stack holds the execution context.

2 Call Stack Introduction

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.

Example:-

1 . Let’s suppose we have a function “greeting”, “sayHi” and we’ve to invoke the “greeting”.

function greeting() {
  sayHi();
}

function sayHi() {
  return "Hi!";
}

// Invoke the `greeting` function
greeting();

2. Know greeting will be include in Call Stack.

3 . We call “SayHi” inside the “greeting()” so “sayHi()” will be included in the call stack.

This Image use for batter understanding of call stack example

4 . “greeting” is steel running and “sayHi” return “Hi!”.

5 . All the execution context of “sayHi” will be destroyed And “sayHi” will be thrown out.

5 . And finally “greeting” will be thrown out.

ASYNCHRONOUS CALLBACK

  1. Sometimes the JavaScript code can take a lot of time and this can block the page render.
  2. JavaScript has asynchronous callbacks for non-blocking behaviour.
  3. JavaScript runtime can do only one thing at a time.
  4. Browser gives us other things which work along with the runtime like Web APIs.
  5. In node.js these are available as C++ APIs.

TASK QUEUE

  1. JavaScript can do only one thing at a time.
  2. The rest are queued to the task queue waiting to be executed.
  3. When we run setTimeout than web APIs will run a timer and push the function provided to setTimeout to the task queue once the timer ends.
  4. These tasks will be pushed to the stack where they can executed.

THE EVENT LOOP

  1. JavaScript has a runtime model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks.
  2. The event loop pushes the tasks from the task queue to the call stack.
  3. We can see how these things work in action :

Source link