Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Js single thread mechanism

  • Only one thread can execute js at a time

Event loop basis

  • Macro task
    • Script (whole code)
      • Any definition ofscriptThe function in the element has a global scope that spans the current document
    • setTimeout
      • The method is mounted on the Window
      • The setTimeout() method sets a timer that executes a function or a specified piece of code when the timer expires.
    • setInterval
      • The method is mounted on the Window
      • The setInterval() method repeatedly calls a function or executes a code segment, with a fixed time delay between calls
    • setImmediate
      • The method is mounted on the Window
      • This method is used to place long-running operations in a callback that is executed as soon as the browser completes the rest of the statement
      • New features are not recommended for use in production environments
    • IO
      • The text flow
    • UI rendering
      • User interface presentation
  • Micro tasks
    • promise
      • A new approach to asynchronous callbacks
    • Obeject.observe
      • All kinds of observation function methods
    • MutationObserve
      • The observer monitors dom changes
  • Task priority
    • promise.nextTick > promise.then > setTimeout > setImmediate

Code sample

        / / macro task
        setTimeout(() = > {
            console.log(2)})Micro / / task
        new Promise((resolve,reject) = > {
            console.log(3)
            resolve()
            console.log(4)
        }).then(() = > {
            // Asynchronous tasks
            console.log(5)})console.log(8)
Copy the code
  • Execution order

Legend of the event loop

Code sample

    
        console.log('script start')

        / / macro task
        setTimeout(() = > {
            console.log('setTimeout')})// Microtask 1 follows the macro task
        Promise.resolve().then(() = > {
            // Microtask 2 follows the macro task
            console.log('promise1')
        }).then(() = > {
            // Microtask 3 follows the macro task
            console.log('promise2')})console.log('script end')
Copy the code

conclusion

  • Get ~ ~