In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use macro tasks and micro tasks in js. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
The following is a question about macro and micro tasks:
SetTimeout (function () {console.log ('1')}); new Promise (function (resolve) {console.log ('2'); resolve ();}). Then (function () {console.log ('3')}); console.log ('4')
What is the execution order of the above code?
Some friends may answer: 2, 4, 4, 1, 3
Think of it this way: don't I know that js is executed line by line, setTimeout is asynchronous, so put it in the back first; go down, execute console.log (2), .then () is asynchronous, put it in the back; go console.log (4); go to the asynchronous queue, first console.log (1); then console.log (3).
I panicked, so I pasted it into my browser to take a look:
Can't believe it.
With confusion, I can only study the operating mechanism of JavaScript!
1. About JavaScript
JavaScript is a single-threaded language, that is, only one task can be completed at a time, and if there are multiple tasks to be executed, they must be queued to be executed (the previous task is completed, and then the next task is executed).
2. JavaScript event loop
Since js is single-threaded, it's like a canteen with only one window, where students need to line up for meals, and js tasks need to be executed sequentially. This mode is easy to execute, but with the increase of requirements, transactions, and requests in the future, this single-threaded mode must be inefficient. As long as there is a task that takes a long time to execute, subsequent tasks cannot be performed during that time.
It is common that the ultra-clear pictures included in the news load very slowly. does our web page have to stay stuck until the pictures are fully displayed? To solve this problem, the JavaScript language divides task execution patterns into synchronous and asynchronous:
Synchronous mode: it is a kind of execution mode mentioned above, in which the latter task waits for the end of the previous task and then executes. The execution order of the program is consistent with the order of the tasks.
Asynchronous mode: each task has one or more callback functions (callback). After the completion of the previous task, instead of executing the next task, the callback function is executed, and the latter task is executed without waiting for the end of the previous task, so the execution order of the program and the order of the tasks are inconsistent and asynchronous.
If the content to be expressed by the map is expressed in words:
Synchronous and asynchronous tasks enter different execution "places", synchronously enter the main thread, asynchronously enter Event Table and register functions.
When the specified thing is done, Event Table moves this function into Event Queue.
If the task in the main thread is empty, it will go to Event Queue to read the corresponding function and enter the main thread for execution.
The above process is repeated over and over again, which is often called Event Loop (event cycle).
Coupled with the code expression:
Let data = []; $.ajax ({url:blog.csdn.net, data:data, success: () = > {console.log ('successfully sent!')}) console.log ('end of code execution')
The above is a simple ajax request code:
Ajax enters Event Table and registers the callback function success.
Execute console.log ('end of code execution').
The ajax event completes, and the callback function success enters Event Queue.
The main thread reads the callback function success from Event Queue and executes it.
I believe that through the above text and code, you have a preliminary understanding of the order in which js is executed. However, this is also the reason why there are friends who answer 2Jing 4jue 1P 3.
However, in fact, there is a way in the asynchronous queue, our interview question, setTimeout and promise. Then () are all in the asynchronous queue! Next, talk about those ways (macro tasks and micro tasks).
3. Macro task and micro task
Everyone understands it differently, because macro and micro tasks are not standard, but the order of execution is uniform in js.
Macro tasks:
# browser Node overall code √√ setTimeout √√ setInterval √√ setImmediatex √ requestAnimationFrame √ xAjax √√ DOM event √√
Micro tasks:
# browser Nodeprocess.nextTickx √ MutationObserver √ xPromise.then catch finally √√
Macro tasks include: overall code, setTimeout, setInterval, setImmediate, Ajax, DOM events
Micro tasks: process.nextTick, MutationObserver, Promise.then catch finally
Process.nextTick is too different, different node implementation is not uniform, do not set the standard
Micro tasks are executed earlier than macro tasks.
Tip: some people like to put the whole code in macro tasks, but I personally don't like it. In my case, it is only the main thread of the first execution. I personally classify macro tasks and micro tasks as asynchronous tasks!
Let's take a look at that face question again:
/ / callback is the asynchronous task setTimeout (function () {/ / macro task console.log ('1')}); new Promise (function (resolve) {console.log ('2'); / / synchronous main thread resolve ();}) .then (function () {/ / micro task console.log ('3')}); console.log ('4') / / synchronous main thread
2: the first one in synchronization, so the first
4: the second in synchronization, so the second
3: micro tasks in asynchronism, so the third
1: macro task in async, so second
So: the result of 2Jing 4jue 3jue 1 comes out!
In addition to this, let's expand:
SetTimeout (() = > {/ / Macro Task queue 1 console.log ('1') / / Task 1 of Macro Task queue 1 setTimeout (() = > {/ / Macro Task queue 3 (Macro tasks in Macro Task queue 1) console.log ('2')}, 0) new Promise (resolve = > {resolve () console.log ('3') / / Task 2 of Macro Task queue 1}). Then () = > microtasks in Macro Task queue 1 console.log ('4')})} 0) setTimeout (() = > {/ / Macro task queue 2 console.log ('5')}, 0) console.log ('6') / / synchronization main thread
Execute the whole code (macro task) console.log ('6') > > Macro task queue 1, Macro task queue 2 bits asynchronously (execute in turn)
Macro task queue 1PUR = >
Console.log ('1')
Console.log ('3')
Micro tasks in console.log ('4') / / Macro tasks
The rest will not be executed first, because it is a macro task in the macro task (console.log (2)), which will be thrown into the task queue.
Macro task queue 2vl = >
Console.log ('5')
Macro Task 3 in Macro Task queue 1
Console.log ('2')
How will the above code be output?
4. Expand macro tasks and micro tasks
The above gives a complex problem, friends might as well think about, this complex situation, how to implement one by one?
6: the first synchronization main thread, so the first
There are no micro tasks in the overall code of script, so macro tasks are executed directly = >
Macro task queue:
Macro Task queue 1
Task 1:console.log (1)
Task 2:console.log (3)
Micro tasks in Macro Task queue 1: console.log (4)
Macro Task queue 3: because he is a macro task in Macro Task queue 1, he is thrown into the task queue. Finally, let's see if there are any macro tasks at the same level in Macro Task queue 1. If so, execute the same level first, and then you can execute Macro Task queue 3! So finally!
Macro Task queue 2
Console.log (5)
So what's the output? It's 6pence, 1pas, 3pr, 4pr, 5pr, pas 2!
Thank you for reading! This is the end of this article on "how to use macro and micro tasks in js". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.