Mohit Bajoria

Software Developer

SetTimeout vs nextTick in VueJS

July 18, 2018


Vue performs DOM updates asynchronously. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop. If the same watcher is triggered multiple times, it will be pushed into the queue only once. This buffered de-duplication is important in avoiding unnecessary calculations and DOM manipulations.

nextTick allows you to do something after you have changed the data and Vue has updated the DOM based on your data change, but before browser has rendered those changes on the page.

Let say you have changed some data, Vue will update the DOM based on the data, These changes are not yet rendered to the screen by the browser. If you used nextTick, your callback gets called now. Then, browser updates the page. If you used setTimeout, your callback would get called only now.

Basically, nextTick allows you to update the DOM explicitly after you have made some changes to the data

Example to visualise the behaviour

<template>
  <div class="hello">
    {{ msg }}
  </div>
</template>

<script>
export default {
  name: 'Hello',
  data() {
    return {
        msg: 'I love VueJS'
    }
  },
  mounted() {
      this.msg = 'VUE is awesome';

      this.$nextTick(() => {
          this.msg = 'VUE is great';
      });
  }
}


</script>

If you see the above example here, you will see VUE is great on screen

Using setTimeout, your callback would get called only after browser updates the page

On the above code, now replace this.$nextTick with setTimeout

<template>
  <div class="hello">
    {{ msg }}
  </div>
</template>

<script>
export default {
  name: 'Hello',
  data() {
    return {
        msg: 'I love VueJS'
    }
  },
  mounted() {
      this.msg = 'VUE is awesome';

      setTimeout(() => {
          this.msg = 'VUE is great';
      });
  }
}
</script>

you will see VUE is awesome before VUE is great Because Vue updated the DOM to VUE is awesome then it gave control to browser. Browser displayed VUE is awesome and then called your callback after which it displayed VUE is great

These changes are so fast we don't notice regularly but it can come handy and can save you from hours of debugging.

Credits - Stackoverflow


Tweaking Webpack configuration using Vue CLI 3

homegithubtwitter