view

introduce

This is the first day of my participation in Gwen Challenge

In JS, there are two types of task queues: Macro tasks and micro tasks. There can be multiple macro task queues and only one microtask queue. So what tasks, what queues are they in?

  • Macro tasks: Script (global task), setTimeout, setInterval, setImmediate, I/O, UI Rendering.
  • Microtasks: Process. nextTick, Promise, Object.observer, MutationObserver.
  • Microtasks are always executed before macro tasks.
setTimeout(() = >console.log("d"), 0)
var r = new Promise(function(resolve, reject){
    resolve()
});
r.then(() = > {
    var begin = Date.now();
    while(Date.now() - begin < 1000);
    console.log("c1")
    new Promise(function(resolve, reject){
        resolve()
    }).then(() = > console.log("c2"))});// output: c1
// output: c2
// output: d
Copy the code

Here we enforce a 1 second execution time so that we can ensure that task C2 is added to the task queue after d. But c2 was printed before D.

var r = new Promise(function(resolve, reject){
    console.log("a");
    resolve()
});
r.then(() = > console.log("c"));
console.log("b")

// output: a
// output: b
// output: c
Copy the code

Analyze the order of asynchronous execution

  • First, analyze how many macro tasks there are
  • Within each macro task, analyze how many microtasks there are
  • According to the call order, determine the micro tasks in the macro task and the execution order
  • According to the trigger rules and call order of macro tasks, determine the execution order of macro tasks
  • Determine the entire sequence
console.log('script start');

Micro / / task
Promise.resolve().then(() = > {
    console.log('p1');
});

/ / macro task
setTimeout(() = > {
    console.log('setTimeout');
}, 0);

var s = new Date(a);while(new Date() - s < 50); / / block 50 ms

Micro / / task
Promise.resolve().then(() = > {
    console.log('p2');
});

console.log('script ent');


/*** output ***/

// one macro task
script start
script ent

// all micro tasks
p1
p2

// one macro task again
setTimeout
Copy the code

The reason for adding 50ms block is that setTimeout delayTime is at least 4ms. To avoid thinking that setTimeout was executed later because of a 4ms delay, we added a 50ms block.

Small thinking

Example :(from winter’s relearn front) – we now want to implement a traffic light, a circular div in green 3 seconds, yellow 1 second, red 2 seconds cycle to change the background color, how would you write this code?

– Use promise to wrap the setTimeout function into a function that can be used asynchronously

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .trafic-light {
      height: 100px;
      width: 100px;
      border-radius: 50%;
      margin: 200px auto 0;
      border: 1px solid #ececec;
    }
  </style>
</head>
<body>
  <div id="trafic-light" class="trafic-light"></div>
</body>
<script>
  let traficEle = document.getElementById('trafic-light');
  function changeTraficLight(color, duration) {
    return new Promise(function (resolve, reject){
      traficEle.style.background = color;
      setTimeout(resolve, duration); })}async function traficScheduler() {
    await changeTraficLight('green'.3000)
    await changeTraficLight('yellow'.1000)
    await changeTraficLight('red'.2000)
    traficScheduler();
  }
  traficScheduler();
</script>
</html>
Copy the code