使用vue實現(xiàn)計時器功能
本文實例為大家分享了vue實現(xiàn)計時器功能的具體代碼,供大家參考,具體內(nèi)容如下
首先我們要知道setTimeout和setInterval的區(qū)別
setTimeout只在指定時間后執(zhí)行一次,代碼如下:
<script> //定時器 異步運行 function hello(){ alert("hello"); } //使用方法名字執(zhí)行方法 var t1 = window.setTimeout(hello,1000); var t2 = window.setTimeout("hello()",3000);//使用字符串執(zhí)行方法 window.clearTimeout(t1);//去掉定時器 </script>
setInterval以指定時間為周期循環(huán)執(zhí)行,代碼如下:
//實時刷新時間單位為毫秒 setInterval('refreshQuery()',8000); /* 刷新查詢 */ function refreshQuery(){ $("#mainTable").datagrid('reload',null); }
一般情況下setTimeout用于延遲執(zhí)行某方法或功能,
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, // 秒的計數(shù) cde : 0, // 分的計數(shù) efg : 0, // 時的計數(shù) } }, 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>
效果如下:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue中消息橫向滾動時setInterval清不掉的問題及解決方法
最近在做項目時,需要進行兩個組件聯(lián)動,一個輪詢獲取到消息,然后將其傳遞給另外一個組件進行橫向滾動展示,結果滾動的速度越來越快。接下來通過本文給大家分享Vue中消息橫向滾動時setInterval清不掉的問題及解決方法,感興趣的朋友一起看看吧2019-08-08Vue3+vantUI3時間組件封裝過程支持選擇年以及年月日時分秒
這篇文章主要介紹了Vue3+vantUI3時間組件封裝過程支持選擇年以及年月日時分秒,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-07-07Ant Design Upload 文件上傳功能的實現(xiàn)
這篇文章主要介紹了Ant Design Upload 文件上傳功能的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04