This is my fourth day of the August Challenge

preface

Js event loops are essential to understanding the execution order of the code we read. Rerendering after virtual DOM comparison in Vue is a reference to this mechanism

Event Loop

Js is a single threaded language, so you can do one thing before you do the next

Js executable code can be divided into synchronous and asynchronous, synchronous code execution is completed before the execution of asynchronous tasks

Asynchronous tasks are divided into macro tasks and micro tasks

  1. Execute synchronization code
  2. Execute the microtask queue
  3. Execute the macro task queue
  4. Repeat 2 => 3 until there is no task queue

Micro tasks

A Promise is a typical microtask

console.log(1)
const p1 = new Promise((resolve, reject) => {
  console.log(2)
  resolve()
})
p1.then(() => {
  console.log(3)
})
console.log(4)
Copy the code

The result of the above execution is

1 2 3 4Copy the code

The function that promise enters belongs to a synchronization environment, so 2 precedes 4

Macro task

SetInterval and setTimeout are two common tasks

console.log(1)
setTimeout(() => {
  console.log(2)
})
console.log(3)
Copy the code

The above execution result

1 2 3Copy the code

Application in VUE

Vue updates the DOM asynchronously, and the updated content forms a queue, which is deduplicated

const count = ref(1);
watchEffect(() => {
    console.log(count.value);
});
const add = () => {
    count.value++;
    count.value++;
};
Copy the code

The stack of count is called twice after the add method is triggered, but watchEffect will only listen for one change, which is the deduplicated asynchronous update queue

$nextTick

const count = ref(1);
watchEffect(() => {
    console.log(count.value);
});
const add = () => {
    count.value++;
    count.value++;
    nextTick(() => {
        console.log('nextTick')
    })
};
Copy the code

Add the nextTick method on top of that, and perform the callback after the DOM has been updated, which can also be understood as after the updated lifecycle hook

With the help of the features of nextTick, you can reasonably complete the operation that needs to rely on DOM

conclusion

  1. Do one thing at a time, do one thing at a time (js single threading feature)
  2. A single loop of macro and microtask queues is an event loop
  3. Vue’s $nextTick mechanism can be understood as a combination of event loops and shake suppression