Home  >  Article  >  Web Front-end  >  $nextTick VS setTimeout, see their differences

$nextTick VS setTimeout, see their differences

青灯夜游
青灯夜游forward
2021-07-14 18:21:302332browse

This article will briefly compare $nextTick and setTimeout to see the differences between them.

$nextTick VS setTimeout, see their differences

A front-end developer (Xiao Zhi) walked into a Vue bar. Ash ordered his favorite cocktail: Nuxt. The bartender is hard at work making it. Then he started chattering to himself.

Xiao Zhi told how he discovered $nextTick under the instance method of Vue 3 and was surprised. Xiaozhi has been using Vue for some time, and he has become accustomed to writing $watch and $emit as instance methods. So, what is $nextTick used for? The Vue documentation says that it "[defers] a callback that is executed after the next DOM update cycle".

But Xiaozhi didn’t believe it.

He went on to tell how he tried to do this:

this.loadingAnimation = true
this.startVeryLongCalculation()
this.completeVeryLongCalculation()
this.loadingAnimation = false

It worked. Why?

nextTickWhat does it do?

nextTickAccepts a callback function that is delayed until the next DOM update cycle. This is just Vue's way of saying, "Hey, if you want to execute a function after the DOM has updated (which rarely happens), I want you to use nextTick instead of setTimeout ".

Vue.nextTick(() => {}) // syntax

The setTimeout and nextTick parameters will be discussed soon. We use this example to visualize the behavior of nextTick:

<template>
  <div>
    {{ currentTime }}
  </div>
</template>

<script>
export default {
  name: &#39;getCurrentTime&#39;,
  data() {
    return {
      currentTime: &#39;&#39;
    }
  },
  mounted() {
    this.currentTime = 3;

    this.$nextTick(() => {
        let date = new Date()
        this.currentTime = date.getFullYear()
    });
  }
}
</script>

Run this code snippet on J computer. It will show 2021 year. It's not that you won't get the same result if you remove nextTick. However, you should understand that Vue will modify the DOM based on the content of the data.

In the above code snippet, Vue updates the DOM to 3, then calls the callback, updates the DOM to 2021, and finally hands control to the browser , the browser will display 2021.

So far, we have looked at nextTick inserting a callback function in the callback queue and executing the function at the appropriate time.

You may be interested in this. The callback in nextTick is used as a microtask in the event loop. The source code of nextTick clearly states that "nextTick behavior utilizes a microtask queue and can be passed through local Promise.then or MutationObserver to access."

setTimeout vs nextTick

Another way to execute a function after a DOM update is to use JavaScript's setTimeout() function.

We will replace the above code with setTimeoutnextTick:

<template>
  <div>
    {{ currentTime }}
  </div>
</template>

<script>
export default {
  name: &#39;getCurrentTime&#39;,
  data() {
    return {
      currentTime: &#39;&#39;
    }
  },
  mounted() {
    this.currentTime = 3;

    setTimeout(() => {
      let date = new Date()
      this.currentTime = date.getFullYear()
    }, 0);
  }
}
</script>

to run this code snippet. First see 3 then 2021. It happens quickly, so you need to refresh your browser if you don't see this behavior.

In the above code snippet, Vue updates the DOM to 3 and provides browser control. Then the browser displays 3, calls the callback function, updates the DOM to 2021, and finally hands control to the browser, and now the browser displays 2021. The implementation of

nextTick is used on browsers that do not support Promise and MutationObserver (IE 6-10 and Opera Mini browsers). setTimeout is used as a fallback method, which prefers setImmediate for browsers that do not support Promise and MutationObserver (IE 10).

When to use nexttick

  • When you want to use setTimeout
  • When you want to make sure the DOM reflects your data
  • When trying to perform an asynchronous operation, errors such as Uncaught (in promise) DOMException were encountered. Remember, Vue updates the DOM asynchronously

Finally, here is an example:

<div id="app">
  <div ref="listScroll" class="scrolledList">
    <ul ref="scrolledHeight">
      <li v-for="month in months">
        {{month}}
      </li>               
    </ul>
  </div>

  <input type="text" placeholder="Add Month" v-model="month">
  <button @click="addMessage" @keyup.enter="addMessage"> Add Month</button>
</div>

<script src="https://unpkg.com/vue@next"> 
  Vue.createApp({
    data() {
      return {
        month: &#39;&#39;,
        months: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Apr&#39;, &#39;May&#39;, &#39;June&#39;, &#39;July&#39;, &#39;Aug&#39;]
      }
    },
    mounted() {
      this.updateScrollNextTick()
    },
    methods: {
      addMessage() {
        if(this.month == &#39;&#39;){
          return
        }

        this.months.push(this.month)
        this.month = &#39;&#39;
        this.updateScrollNextTick()
      },
      updateScrollNextTick () {
        let scrolledHeight = this.$refs.scrolledHeight.clientHeight

        this.$nextTick(() => {
          this.$refs.listScroll.scrollTo({
            behavior: &#39;smooth&#39;,
            top: scrolledHeight
          })
        })
      }
    },
  })
  .mount("#app")
</script>

Sample address: https://codepen.io/ammezie/pen/OJpOvQE

Main part:

$nextTick VS setTimeout, see their differences

Running result:

$nextTick VS setTimeout, see their differences

In the above code snippet , we want to get a smooth scrolling down effect when a new item is added to the list. Take a look at the code and try modifying it to remove the nextTick and you'll lose that smooth scrolling effect. You can also try using setTimeout instead of nextTick.

Summary

In this article, we explored how nextTick works. We take a closer look at how it differs from normal JavaScript setTimeout and cover practical use cases.

English original address: https://blog.logrocket.com/understanding-nexttick-in-vue-js/

Author: Chimezie Enyinnaya

Translated Author: Front-end Xiaozhi

Reprint address: https://segmentfault.com/a/1190000040246186

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of $nextTick VS setTimeout, see their differences. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete