ForeveHG / Frontend-Daily-Interview

学习,尝试回答一些前端面试题
1 stars 0 forks source link

44. 谈一谈 nextTick 的原理 #45

Open ForeveHG opened 4 years ago

ForeveHG commented 4 years ago

在代码执行过程中(当前tick),第一次调用nextTick时,会创建一个微任务或宏任务,并将传入的回调函数加入callbacks队列中,在同一轮事件循环中,如果多次调用nextTick,不再创建微任务或宏任务,只用将回调函数加入callbacks队列,首次nextTIck时创建的微任务或宏任务的作用就是执行callbacks队列中的回调函数,具体的什么时候执行要看创建的是微任务还是宏任务,如果浏览器支持Promise就创建微任务,否则创建的就是宏任务,微任务在当前tick的同步代码执行结束后立刻执行,宏任务在下一轮tick执行

ForeveHG commented 4 years ago

下面代码的执行结果是什么?

<template>
  <div>
    <span ref="span">{{ msg }}</span>
    <button @click="click">click</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "hello",
    };
  },
  methods: {
    click() {
      this.msg = "world";
      Promise.resolve().then(() => {
        console.log(1);
      });
      this.$nextTick(function() {
        console.log(2);
      });
      setTimeout(function() {
        console.log(3);
      });
      this.$nextTick().then(() => {
        console.log(4);
      });
      console.log(this.$refs.span.innerHTML);
      this.$nextTick(function() {
        console.log(this.$refs.span.innerHTML);
      });
      Promise.resolve().then(() => {
        console.log(5);
      });
      this.$nextTick(function() {
        console.log(6);
      });
      this.$nextTick().then(() => {
        console.log(7);
      });
      this.$nextTick(function() {
        console.log(8);
      });
    },
  },
};
</script>
ForeveHG commented 4 years ago
答案
hello
2
word
6 
8 
1 
5 
4 
7 
3