Understanding of asynchronous JavaScript Macrotask and Microtask (RPM)

Source: Internet
Author: User

This knowledge point ...

Https://blog.keifergu.me/2017/03/23/difference-between-javascript-macrotask-and-microtask/?hmsr=toutiao.io &utm_medium=toutiao.io&utm_source=toutiao.io

Front-end Base Advanced series

This system is also super cock!!

http://www.jianshu.com/p/cd3fee40ef59

=======================

Macrotask and Microtask are all part of the asynchronous task mentioned above, let's look at what APIs they are:

    • macrotasks: setTimeout , setInterval , setImmediate , I/O, UI rendering
    • microtasks: process.nextTick , Promises , Object.observe (OBSOLETE),MutationObserver

The task queue is divided into Macrotasks and microtasks, while the Promise functions in the then methods are pushed into the microtasks queue, and setTimeout the tasks are pushed into the macrotasks queue. in each event loop, Macrotask only extracts one execution, and microtask is extracted until the microtasks queue is emptied .

Note: Under normal circumstances, macrotask queues we will be directly called task queues, only microtask queues will be specifically indicated.

So that is, if one of my microtask tasks pushes a task into the Microtasks queue, the Microtasks task continues to run until the task queue is exhausted after the main thread finishes the task.

And the event loop will only go into the stack one macrotask at a time, and the main thread will check the Microtasks queue and complete all the tasks before executing the Macrotask after performing the task.

=======================

Test code:

<script>    console.log (' script start ');    SetTimeout (function() {        console.log (' setTimeout ');    },0);        Promise.resolve (). Then (function() {        console.log (' Promise ');    }). Then (function() {    console.log (' promise2 ');}); Console.log (' script end '); </script>

Understanding of asynchronous JavaScript Macrotask and Microtask (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.