DEV Community

Cover image for Do you know Javascript ?
Manas Mishra
Manas Mishra

Posted on

Do you know Javascript ?

We already know that javascript is single threaded, but the way it works is totally different from other programming languages like C and Java.

The Event Loop

Javascript has a runtime model, which is based on an event loop. It's responsible for three things:

  • Executing the code.
  • Collecting and Processing Events
  • Executing Queued tasks (actually sub-tasks).

JS event Loop diagram

Stack

function foo(b) {
  let a = 10
  return a + b + 11
}

function bar(x) {
  let y = 3
  return foo(x * y)
}

const baz = bar(7) // assigns 42 to baz
Enter fullscreen mode Exit fullscreen mode

In the above example, the order of operation will be in the following manner.

  1. When bar is being called, the first frame is created, which was containing references to bar's argument and local variables.
  2. When bar calls foo, a second frame is created and pushed on top of the first one, containing references to foo's arguments and local variables.

Heap

Objects are allocated in a heap which is just a name to denote a large (mostly unstructured) region of memory.

Queue

A JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function that gets called to handle the message.

At some point during the event loop, the runtime starts handling the messages on the queue, starting with the oldest one. To do so, the message is removed from the queue and its corresponding function is called with the message as an input parameter. As always, calling a function creates a new stack frame for that function's use.

The processing of functions continues until the stack is once again empty. Then, the event loop will process the next message in the queue (if there is one).

Adding Messages

The function setTimeout is called with 2 arguments: a message to add to the queue, and a time value (optional; defaults to 0). The time value represents the (minimum) delay after which the message will be pushed into the queue. If there is no other message in the queue, and the stack is empty, the message is processed right after the delay. However, if there are messages, the setTimeout message will have to wait for other messages to be processed. For this reason, the second argument indicates a minimum time—not a guaranteed time.

const seconds = new Date().getSeconds();

setTimeout(function() {
  // prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
  console.log(`Ran after ${new Date().getSeconds() - seconds} seconds`);
}, 500)

while (true) {
  if (new Date().getSeconds() - seconds >= 2) {
    console.log("Good, looped for 2 seconds")
    break;
  }
}

Enter fullscreen mode Exit fullscreen mode

Final Words

The above article codes are being taken from MDN docs about the event loop

Top comments (0)