使用vue实现计时器功能

2022-07-22,,

本文实例为大家分享了vue实现计时器功能的具体代码,供大家参考,具体内容如下

首先我们要知道settimeout和setinterval的区别

settimeout只在指定时间后执行一次,代码如下:

<script>  
//定时器 异步运行  
function hello(){  
alert("hello");  
}  
//使用方法名字执行方法  
var t1 = window.settimeout(hello,1000);  
var t2 = window.settimeout("hello()",3000);//使用字符串执行方法  
window.cleartimeout(t1);//去掉定时器  
</script>

setinterval以指定时间为周期循环执行,代码如下:

//实时刷新时间单位为毫秒  
setinterval('refreshquery()',8000);   
/* 刷新查询 */  
function refreshquery(){  
   $("#maintable").datagrid('reload',null);  
}

一般情况下settimeout用于延迟执行某方法或功能,
setinterval则一般用于刷新表单,对于一些表单的实时指定时间刷新同步

计时器

html代码

<div class="father">
  <ul>
   <li>{{one}}<span>:</span></li>
   <li>{{two}}<span>:</span></li>
   <li>{{three}}</li>
  </ul>
  <el-button type="primary" @click="starthandler">开始</el-button>
  <el-button type="primary" @click="endhandler">暂停</el-button>
</div>

javascript代码

<script>
export default {
  name: 'helloworld',
  data(){
   return {
  flag: null,
  one : '00', // 时
  two : '00', // 分
  three : '00', // 秒
  abc : 0, // 秒的计数
  cde : 0, // 分的计数
  efg : 0, // 时的计数
   }
  },
  props: {
    msg: string
  },
  mounted() {
   
  },
  methods:{
  // 开始计时
 starthandler(){
  this.flag = setinterval(()=>{
   if(this.three === 60 || this.three === '60'){
    this.three = '00';
    this.abc = 0;
    if(this.two === 60 || this.two === '60'){
     this.two = '00';
     this.cde = 0;
     if(this.efg+1 <= 9){
      this.efg++;
      this.one = '0' + this.efg;
     }else{
      this.efg++;
      this.one = this.efg;
     }
    }else{
     if(this.cde+1 <= 9){
      this.cde++;
      this.two = '0' + this.cde;
     }else{
      this.cde++;
      this.two = this.cde;
     }
    }
   }else{
    if(this.abc+1 <= 9){
     this.abc++;
     this.three = '0' + this.abc;
    }else{
     this.abc++;
     this.three=this.abc;
    }
   }
   
  },100)
 },
 // 暂停计时
 endhandler(){
  this.flag = clearinterval(this.flag)
 }
  }
}
</script>

效果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《使用vue实现计时器功能.doc》

下载本文的Word格式文档,以方便收藏与打印。