What is a JS event loop?

Javascript is single-threaded. When executing code, it will execute line by line. When it meets asynchronous code (initiate ajax request, execute setTimeout), it will suspend and put it into message queue, continue to execute the following code, and execute the message queue code after execution.

The test code

<script>
    console.log('start')
    setTimeout(() = > {
      console.log('setTimeout start')},0)
    for (var i = 0; i < 10; i++) {
      console.log('Loop execution')}const p1 = new Promise((resolve, reject) = > {
      console.log('Constructor execution')
      resolve(1)
    }).then(res= > {
      console.log('then1', res)
      return res
    }).catch(err= > {
      console.log('err', err);
    })

    Promise.resolve(2).then(_= > console.log('then2'.2))
    console.log('end')
  </script>
Copy the code

Print result:

Code modification to add mid-click tasks

To be effective, I changed the timer to run after 4s and the for loop to run 3000 times when we re-execute the code and click the button continuously

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <title>Document</title> </head> <body> <button onclick="onclick1 "> </button> <script> Console. log('start') function onClick1 () {console.log(' button clicked '); } setTimeout(() => { console.log('setTimeout start1') }, 1000) setTimeout(() => { console.log('setTimeout start2') }, 4000) for (var i = 0; i < 3000; I++) {console.log(' loop ')} const p1 = new Promise((resolve, resolve, Reject) => {console.log(' constructor execution ') resolve(1)}).then(res => {console.log('then1', res) return res }).catch(err => { console.log('err', err); }) Promise.resolve(2).then(_ => console.log('then2', 2)) console.log('end') </script> </body> </html>Copy the code

The print result is as follows:

conclusion

  • Javascript is single-threaded and suspends when asynchronous code is encountered
  • SetTimeout,setInterval’s callback function is added to the message queue of the macro task
  • The function in the Promise’s then() method is added to the microtask’s message queue
  • In an event loop, when the main thread is idle (the stack is empty), tasks in the microtask message queue are executed first until the microtask queue is empty
  • Micro task queue is empty, the main thread will execute the macro task queue inside meet when loops task, not necessarily to empty the queue, for example, would not be in the set of 4 s timer event loop execution, we click on the button 13 times timer, printed after the instructions in the 13th event loop to perform a second timer macro task