The original linkmedium.com/@Rahulx1/un…

In this article, we’ll delve into how javascript works, how it executes our asynchronous javascript code, the execution sequence of Promise and setTimeout, how it generates a stack trace, and more.

As most developers know, Javascript is single-threaded, which means that two statements in Javascript cannot be executed in parallel. It can only be executed line by line, which means that every javascript statement is synchronized and blocked. But there is a way to run your code asynchronously, if you use the setTimeout() function, the browser-provided Web API, which ensures that your code executes after a specified time (in milliseconds). Sample code:

console.log('Message 1');

setTimeout(function() {
   console.log('Message 2');
}, 100);

console.log('Message 3');
Copy the code

SetTimeout The first argument is the callback function and the second argument is the time in milliseconds. There are also two optional parameters, see MDN for details.

After the above statement is executed, the browser prints “Message 1” and “Message 3” before printing “Message 2”. This is where the event loop comes in, ensuring that your asynchronous code runs after all the synchronous code has been executed.

Event Loop Visualization

Stack: This is where all of your javascript code is pushed and executed one by one when the parser reads your program, and pops up when it’s done. If your statement is asynchronous: contains a setTimeout, Ajax (), Promise, or click Event, the code is forwarded to the Event table, which is responsible for moving your asynchronous code to the callback/Event queue after the specified time.

Heap: This is where all memory allocation occurs for variables that you define in your program.

Callback Queue: This is where your asynchronous code is pushed to and waiting to be executed.

Event Loop: An Event Loop that keeps running and checks the main stack if any frames are to be executed; If not, it checks the callback queue, and if there is code to execute in the callback queue, it pops the message from it onto the main stack for execution.

Job Queue: In addition to the callback Queue, the browser has introduced another Queue, the “Job Queue”, which is reserved only for the new Promise() function. When you use promise in your code and add the.then() method, it is a callback method. Once promise Returned /resolve, these Thenable methods are added to the job queue and executed.

Looking at the following code example, can you predict the order of output?

console.log('Message no. 1: Sync');

setTimeout(function() {
   console.log('Message no. 2: setTimeout');
}, 0);

var promise = new Promise(function(resolve, reject) {
   resolve();
});

promise.then(function(resolve) {
   console.log('Message no. 3: 1st Promise');
})
.then(function(resolve) {
   console.log('Message no. 4: 2nd Promise');
});

console.log('Message no. 5: Sync');
Copy the code

Tip: All of the Promise’s Thenable callbacks are called first, then the setTimeout callback is called.

The correct input result is as follows:

// Message no. 1: Sync
// Message no. 5: Sync
// Message no. 3: 1st Promise
// Message no. 4: 2nd Promise
// Message no. 2: setTimeout
Copy the code

Why? : Job Queue performs the callback first. If the event loop tick enters the Job Queue, it executes all jobs in the Job Queue until it is empty and then moves to the callback Queue.

If you want to learn more about why Promises are called before setTimeout, you can check out Jake Archibald’s article on Tasks, Microtasks, queues, and scheduling for a more detailed and easy-to-understand explanation.

Code execution considerations

  • Your asynchronous code will run after the “main stack” has executed all its tasks.
  • Asynchronous code cannot interrupt current statements/functions in the stack until they have finished running. Once your asynchronous code is ready to execute, it waits for the main stack to be empty before executing.
  • This also means that there is no guarantee that your setTimeout() or any other asynchronous code will run after the time you specify. This time is the minimum time your code will execute, and may be delayed if the main stack is busy executing existing code

In the following example, the first output will be “Message 2”, followed by “Message 1”, and even though setTimeout is set to run after 0 ms, it cannot execute immediately because the main thread is busy. When the browser encounters setTimeout, it pops it off the main stack into the callback queue, where it waits for the main stack to complete the second console.log, and then setTimeout returns to the main stack and runs the first console.log.

setTimeout(function() {
    console.log('Message 1')},0);

console.log('Message 2');
Copy the code

If you do too many heavy computations, it will make the browser unresponsive because your main thread is blocked and can’t handle any other tasks. Therefore, users will not be able to make any clicks on your web page. The browser throws a “script is taking too long” error and gives you the option to “terminate the script” or “wait.”

Optional. Error stack trace

We already know that if the interpreter encounters a function, that function gets pushed onto the stack, now if that function calls another function, that function call gets pushed onto the top of the stack, and the chain continues until a function completes or returns something, It is then simply removed from the stack and the context is returned to the function that called the last function, and execution continues.

This function call stack helps the browser provide you with a stack trace of errors that occurred in a particular function. Such as:

function func1 () {
  // Accessing an undefined variable throws an error
  console.log(err);
}

function func2 () {
 func1();
}

function func3 () {
 func2()
}

// Calling func3 causes func1 to fail
func3();
Copy the code

As you can see in the error stack trace, the error occurs in the func1 function, which is called on line 1. The third line is the location of the console, line 7 is in func2, and then line 11, func2, is called in func3.

When to use event loops?

  • When you need to do heavy calculations, you don’t need to run them sequentially, which means you can execute the next statement without it. In this case, the main thread is not blocked because of the calculation.
  • When you want to execute your code last, after all other statements/functions have been executed.

Eggs links: 2014. Jsconf. Eu/speakers/ph…