What is the event – loop

  • Js is single threaded and asynchrony needs to be implemented based on callback
  • Event-loop is how asynchronous callbacks are implemented

For example, setTimeout

console.log(1);
setTimeout(function cb1() {
  console.log(2);
}, 0);

console.log(3)
1
3
2
Copy the code

How does the JS code execute

  1. From front to back, row by rowcall stackIf a line fails, the following code stops execution
  2. All synchronous codes are executed before asynchronous codes are executed. If asynchronous codes occur, they are placed in an asynchronous queue and wait for an opportunity
  3. Synchronization code once executedcall-stackIf null, the event-loop event loop mechanism is triggered
    1. Event-loop iterates through the callback queue to determine whether a callback exists
    2. For example,web-apiThe callback function is pushed into the queue when the timer in
    3. Event-loop determines the existence of the function and executes it
    4. The contents of the function body are putcall-stackPerformed in the
    5. Repeat the above steps

DOM events and event-loops

<body>
    <button onclick="fn()">submit</button>
</body>
<script>
    console.log(1);
    function fn() {
        console.log(2);
    }
    console.log(3);
</script>
Copy the code

For example, the DOM click event above is also a callback based on event-loop in nature, but the timing is different. Timer is triggered by time, while DOM is triggered by user click