Categories
Vue Answers

How to create a simple 10 seconds countdown in Vue.js?

Spread the love

Sometimes, we want to create a simple 10 seconds countdown in Vue.js.

In this article, we’ll look at how to create a simple 10 seconds countdown in Vue.js.

How to create a simple 10 seconds countdown in Vue.js?

To create a simple 10 seconds countdown in Vue.js, we can use the setInterval.

For instance, we write

<template>
  <div>
    {{ countDown }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      countDown: 10,
    };
  },
  method: {
    countDownTimer() {
      const timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    },
  },
  mounted() {
    this.countDownTimer();
  },
};
</script>

to create the countDownTimer method.

In it, we call setInterval with a callback that checks if this.countDown is bigger than 0.

If it is, we decrement this.countDown by 1.

Otherwise, we call clearInterval to clear the timer.

The callback runs every 1000 milliseconds which is 1 second.

We call countDownTimer in the mounted hook to run the code when the component is mounted.

The countDown value is displayed in the template.

Conclusion

To create a simple 10 seconds countdown in Vue.js, we can use the setInterval.

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 *