Knowledge of bedding

  • JavaScript has always been a single-threaded language

  • The interpretation of the I

Java can use new Thread(task) to execute the same task, but not JS. Web workers mainly solve the output of time-consuming tasks with large computation

public class AccumulateWrong {

  private static int count = 0;

  public static void main(String[] args) throws Exception {
      Runnable task = new Runnable() {
          public void run() {
              for(int i = 0; i < 1000000; ++i) { count += 1; }}}; Thread t1 = new Thread(task); Thread t2 = new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("count = "+ count); }}Copy the code

What is an Event loop?

In a broad sense, event loop is a scheduling mechanism used by user agents to coordinate various events, user interactions, script execution, network activities and other execution opportunities.

Event loop in browser

Macrotask and microtask types

In the browser context, MacroTasks come in the following categories:

  • When scripts corresponding to external or internal script tags are loaded, executing those scripts is a MacroTask
  • When the user clicks a button on the page, the execution of the handler after the click event is distributed is a MacroTask
  • The execution of the callback passed in when setTimeout or setInterval is called is a MacroTask
  • The execution of the callback passed in when the non-standard global method setImmediate() is called is a MacroTask
  • The callback execution passed in when requestAnimationFrame is called is a MacroTask
  • .

Promise

  • The execution of the callback passed in when the Promise object calls then/catch/finally is a microtask;
  • When queueMicrotask(fn) is explicitly called to enqueue a microtask, the execution of the FN function is a microtask;
  • The new MutationObserver() passes the callback execution as a microtask;
  • Object.observe() incoming callback execution is a microtask.

conclusion

reference

  • Into the Event Loop
  • Event Loop Interview questions
  • One of the best