Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a simple 10 seconds countdown in Vue.js

I want to do a simple countdown from 10 to 0

I found solution online using normal javascript but let say I want to do it in Vue . The solution in Jquery

Create a simple 10 second countdown

<template>
   {{ countDown }}

</template>

<script>
  export default {
    computed: {
       countDown() {
         // How do i do the simple countdown here?
       }

    }

  }

</script>

How do I recreate the same functionality in Vue.js?

Thanks

like image 523
sinusGob Avatar asked Apr 20 '19 12:04

sinusGob


People also ask

How do you make a 10 second timer in JavaScript?

To create a simple 10 second countdown with JavaScript, we use the setInterval method. to add a progress element. let timeleft = 10; const downloadTimer = setInterval(() => { if (timeleft <= 0) { clearInterval(downloadTimer); } document. getElementById("progressBar").

What is VUE method JavaScript?

A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.


4 Answers

Whilst the accepted answer works, and is great, it can actually be achieved in a slightly simpler way by utilising Vue.js watchers:

<template>
    {{ timerCount }}
</template>

<script>

    export default {

        data() {
            return {
                timerCount: 30
            }
        },

        watch: {

            timerCount: {
                handler(value) {

                    if (value > 0) {
                        setTimeout(() => {
                            this.timerCount--;
                        }, 1000);
                    }

                },
                immediate: true // This ensures the watcher is triggered upon creation
            }

        }
    }

</script>

The benefit of using this method is that the timer can be immediately reset by simply setting the value of timerCount.

If you would like to play/pause the timer, then you can achieve this like so (note - this is not a perfect solution as it will round to the nearest second):

<template>
    {{ timerCount }}
</template>

<script>

    export default {

        data() {
            return {
                timerEnabled: true,
                timerCount: 30
            }
        },

        watch: {

            timerEnabled(value) {
                if (value) {
                    setTimeout(() => {
                        this.timerCount--;
                    }, 1000);
                }
            },

            timerCount: {
                handler(value) {

                    if (value > 0 && this.timerEnabled) {
                        setTimeout(() => {
                            this.timerCount--;
                        }, 1000);
                    }

                },
                immediate: true // This ensures the watcher is triggered upon creation
            }

        }

        methods: {

            play() {
                this.timerEnabled = true;
            },

            pause() {
                this.timerEnabled = false;
            }

        }

    }

</script>
like image 59
Ben Carey Avatar answered Oct 24 '22 03:10

Ben Carey


Please check if this works for you.

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

<script>
    export default {
        data () {
            return {
                countDown: 10
            }
        },
        methods: {
            countDownTimer () {
                if (this.countDown > 0) {
                    setTimeout(() => {
                        this.countDown -= 1
                        this.countDownTimer()
                    }, 1000)
                }
            }
        },
        created () {
            this.countDownTimer()
        }
    }
</script>
like image 24
Tomonso Ejang Avatar answered Oct 24 '22 04:10

Tomonso Ejang


Here is a component I made for a countdown timer :

<template>
  <div>
    <slot :hour="hour" :min="min" :sec="sec"></slot>
  </div>
</template>

<script>
export default {
  props : {
    endDate : {  // pass date object till when you want to run the timer
      type : Date,
      default(){
        return new Date()
      }
    },
    negative : {  // optional, should countdown after 0 to negative
      type : Boolean,
      default : false
    }
  },
  data(){
    return{
      now : new Date(),
      timer : null
    }
  },
  computed:{
    hour(){
      let h = Math.trunc((this.endDate - this.now) / 1000 / 3600);
      return h>9?h:'0'+h;
    },
    min(){
      let m = Math.trunc((this.endDate - this.now) / 1000 / 60) % 60;
      return m>9?m:'0'+m;
    },
    sec(){
      let s = Math.trunc((this.endDate - this.now)/1000) % 60
      return s>9?s:'0'+s;
    }
  },
  watch : {
    endDate : {
      immediate : true,
      handler(newVal){
        if(this.timer){
          clearInterval(this.timer)
        }
        this.timer = setInterval(()=>{
          this.now = new Date()
          if(this.negative)
            return
          if(this.now > newVal){
            this.now = newVal
            this.$emit('endTime')
            clearInterval(this.timer)
          }
        }, 1000)
      }
    }
  },
  beforeDestroy(){
    clearInterval(this.timer)
  }
}
</script>
like image 9
user8805101 Avatar answered Oct 24 '22 03:10

user8805101


Make it a component so you can re-use it.

<body>
    <div id="app">
        <counter></counter>
        <counter></counter>
        <counter></counter>
    </div>
    <script>
        Vue.component('counter', {
            template: '<button v-on:click="countDownTimer()">{{ countDown }}</button>',
            data: function () {
                return {
                    countDown: 10,
                    countDownTimer() {
                        if (this.countDown > 0) {
                            setTimeout(() => {
                                this.countDown -= 1
                                this.countDownTimer();
                            }, 1000)
                        }
                    }
                }
            }
        })

        const app = new Vue({
            el: '#app'
        })
    </script>
</body>
like image 1
Lord Avatar answered Oct 24 '22 04:10

Lord