In j**ascript, macro-task and micro-task refer to two types of asynchronous operations.
Macro tasks typically include the following actions:
SetTimeout and SetInterval TimersFunction EventsFunctions (e.g., mouse clicks, keyboard input, etc.)Functions requested by AJAX requestsAnimationFramesFunction Script tagsOnLoad and OnError eventsWhen a macro task starts executing, the j**Ascript engine puts it at the bottom of the call stack and then moves on to the others. When the call stack is empty, the j**ascript engine takes the next macro task and executes it.
Microtasks typically include the following actions:
Promise's function: generator, mutationobserver, and processnexttick(node.JS) When a microtask is added to the task queue, it is executed as soon as the current macro task is executed, rather than waiting for the next macro task to start executing. This allows the microtask to process the results of an asynchronous operation during the execution of the current macro task, improving the responsiveness of the application.
In j**ascript, macro tasks and microtasks have different execution priorities. Typically, microtasks take precedence over macrotasks, that is, in a macro task, if a micro task exists, then the micro task will take precedence over the macro task execution.
Specifically, when a macro task starts to execute, if microtasks are generated during its execution, these microtasks will be added to the microtask queue and wait for the current macro task to be executed immediately after the execution is completed. If a new microtask is generated in the process, the microtask is executed until the microtask queue is empty, and then the j**ascript engine moves on to the next macrotask.
For example, the following demonstrates the order in which macro and microtasks are executed:
console.log('start');settimeout(function() 0);promise.resolve().then(function() console.log('end');In the above, the synchronization is performed firstlog('start') and consolelog('end')。Next, add a macro task using settimeout, and then use promiseresolve().Then add a microtask. Because microtasks take precedence over macro tasks, the promise's function is executed before the settimeout function. Therefore, the output order of the above ** is as follows:
startendpromisesettimeout