使用vue实现计时器功能

Chloe ·
更新时间:2024-09-20
· 828 次阅读

本文实例为大家分享了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 计时器

需要 登录 后方可回复, 如果你还没有账号请 注册新账号