What is event Loop?

Let’s start with a piece of code

Console. log('script start') setTimeout(() => {conso.log('timeOut')}, 0) conosle.log('script end') script start script end timeOutCopy the code

Why is timeOut printed at the end? Because this is how JsCode runs in the browser.

When executing our JS code, we will first execute it from top to bottom, going through one stack. However, when we encounter asynchronous tasks, we will suspend them first, and add them to the specified task queue (macro task or micro task) when the execution stack is empty. Js thread from the task queue take out a small task to perform (if there is a small task), by the time the micro task queue is empty, will go to macro task queue a task execution, if produce micro task in the macro task, will produce micro tasks Put detail task queue, until the micro task completes (micro task queue is empty), The macro tasks in the browser include: setInterval setTimeout requestAnimationFrame Microtasks include: promise.then mutationObserveCopy the code

The V8 engine in the browser is a multi-threaded engine, which includes:

  1. Render thread (render page, js thread can manipulate DOM, will affect rendering, so render thread and JS thread are mutually exclusive)
  2. Js thread (executes JS code)
  3. Timer threads (setTimeout, etc.)
  4. HTTP threads (AJAC requests)
  5. Event trigger thread (user interaction)

If there is a user click event in the event cycle, a task will be added to the macro task queue. If the execution time of the task in the queue is too long, the callback of the user click event will be delayed. Because the browser’s rendering is about 16ms per frame, the user will feel the page is stuck