Categories
Vue Answers

How to use setInterval in a Vue component?

Spread the love

Sometimes, we want to use setInterval in a Vue component.

In this article, we’ll look at how to use setInterval in a Vue component.

How to use setInterval in a Vue component?

To use setInterval in a Vue component, we call it with a callback.

For instance, we write

<script>
//...

export default {
  //...
  methods: {
    todo() {
      this.intervalid = setInterval(() => {
        this.changes = (Math.random() * 100).toFixed(2) + "%";
      }, 3000);
    },
  },
  //...
};
</script>

to call setInterval with a function that sets the value of this.changes every 3 seconds.

We call it with an arrow function so this is still the Vue component instance inside the setInterval callback.

Conclusion

To use setInterval in a Vue component, we call it with a callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *