vue Implementation of Simple Timer Component

  • 2021-11-10 08:36:33
  • OfStack

It is inevitable to encounter the need for real-time refresh in doing projects, Advertising animation appears in turn and so on, Just recently, based on business requirements, it is necessary to implement a timer for accumulating call duration. At this time, it is necessary for timers to step onto our code stage. In fact, the principle of timers is realized through timers. Before writing business requirements, I will first talk about some knowledge about timers.

The window object provides two methods to achieve the effects of the timer, window. setTimeout () and window. setInterval.

In Javascript, Code 1 generally executes synchronously, but the timer executes asynchronously.


window.setTimeout(callback,delay);   //callback: Callback function  delay : Time interval duration 
window.setInterval(callback,delay);

The timer is divided into an interval timer setInterval and a delay timer setTimeout

So what's the difference between them?

setInterval to the specified time cycle for the cycle of execution, 1 for refreshing forms, complex animation cycle execution, for 1 of the forms of real-time specified time refresh synchronization setTimeout is only executed once after the specified time. Like some websites, there will be a pop-up advertisement just after entering, and setTimeout is generally used

After understanding the basic knowledge of timer, you can realize the function next.

HTML


<template>
    <div class="timer">
    <div>{{nowTime}}</div>
    </div>
</template>

Javascript


<script>
    export default {
    name: 'Timer',
    data () {
     return {
      timer: null,
      nowTime:"",
      hour: 0,
      minutes: 0,
      seconds: 0
      }
    },
    created () {
    this.timer = setInterval(this.startTimer, 1000);
    },
    destroyed () {
    clearInterval(this.timer);
    },
    
    methods: {
    startTimer () {
     // It is recommended to clear the timer before starting it to avoid the accumulation of timers and unexpected occurrences bug
     if(this.timer) {
   clearInterval(this.timer);
  }
     this.seconds += 1;
     if (this.seconds >= 60) {
      this.seconds = 0;
      this.minutes= this.minutes+ 1;
     }
     if (this.minutes>= 60) {
      this.minutes= 0;
      this.hour = this.hour + 1;
     }
     this.nowTime = this.toZero(this.hour): this.toZero(this.minutes):this.toZero(this.seconds)
    },
     toZero(timeNumber) {
     return timeNumber<10?"0"+timeNumber : timeNumber
   },
 }
}
</script>

In this way, a simple timer component will be realized. In fact, there are other implementation ideas. If you encounter similar needs in future development, you can learn from it and hope it will be helpful to you.


Related articles: