In asynchronous JavaScript, there are two ways to schedule tasks - Microtask Queue and Callback Queue. The JavaScript engine handles these two queues differently.
Microtask Queue is a task queue that is executed after the current task. The microtask queue is processed by the JavaScript engine before moving to the next task in the callback queue.
The following is an example of how the microtask queue works -
<!doctype html> <html> <head> <title>Examples</title> </head> <body> <div id="result"></div> <script> console.log('start'); setTimeout(function() { console.log('setTimeout'); }, 0); Promise.resolve().then(function() { console.log('promise resolve'); }); console.log('end'); </script> </body> </html>
In the above example, the "setTimeout" callback is added to the callback in queue. "Promise.resolve" is added to the microtask queue. The JavaScript engine will first execute all tasks in the microtask queue before entering the callback queue.
So the output of the above code will be (In the console) -
start end promise resolve setTimeout
Callback Queue is A queue of tasks to be executed after the current task. Callback Queue Processed by the JavaScript engine after executing all tasks in the microtask queue.
The following is an example of how the callback queue works -
<!doctype html> <html> <head> <title>Examples</title> </head> <body> <div id="result"></div> <script> console.log('start'); setTimeout(function() { console.log('setTimeout'); }, 0); console.log('end'); </script> </body> </html>
In the above example, the 'setTimeout' callback is added to the callback queue middle. The JavaScript engine will execute the "setTimeout" callback after executing all code in the current task.
So the output of the above code will be (In the console) -
start end setTimeout
Microtasks Queues and Callbacks Some differences between Queues are-
##Microtask Queues are processed by the JavaScript engine and then Then move to the next task in the callback queue. CallbackThe queue is processed by the JavaScript engine after all tasks in the microtask queue are executed.
Microtask Processed after the current task of the queue is completed. CallbackThe queue is processed after the microtask queue is empty.
MicrotasksThe queue is processed in a separate event loop. CallbacksThe queue is processed in the same event loop.
The above is the detailed content of What is the difference between microtask queue and callback queue in asynchronous JavaScript?. For more information, please follow other related articles on the PHP Chinese website!