vue實現簡易計時器組件
在做項目中難免會碰到需要實時刷新,廣告動畫依次出現等等需求,剛最近基于業務需求,需要實現一個累加通話時長的計時器,這時候就需要定時器登上我們的代碼舞臺了,其實對于計時器,它的原理就是通過定時器來實現的,那么在寫業務需求之前,我先說說關于定時器的一些知識。
window對象提供了兩個方法來實現定時器的效果,分別是window.setTimeout()和window.setInterval。
在Javascript中,代碼一般都是同步執行的,但定時器卻是異步執行的。
window.setTimeout(callback,delay); //callback:回調函數 delay:時間間隔時長window.setInterval(callback,delay);
定時器分為隔時定時器setInterval和延時定時器setTimeout
那么它們兩到底有什么區別呢?
setInterval以指定時間為周期循環執行,一般用于刷新表單、復雜動畫的循環執行,對于一些表單的實時指定時間刷新同步 setTimeout只在指定時間后執行一次,像有些網站剛進去會出現一個彈窗廣告,一般都是用的setTimeout了解了定時器的基本知識之后,那么接下來就可以進行功能的實現了。
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 () { //建議開啟定時器前,先清除定時器,避免定時器累加,出現不可預期的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>
這樣,一個簡單的計時器組件就實現好了,其實還有其他的實現思路,如果以后開發碰到了類似的需求,可以借鑒,希望對你們有所幫助。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. php測試程序運行速度和頁面執行速度的代碼2. ASP中常用的22個FSO文件操作函數整理3. 三個不常見的 HTML5 實用新特性簡介4. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析5. ASP調用WebService轉化成JSON數據,附json.min.asp6. SharePoint Server 2019新特性介紹7. React+umi+typeScript創建項目的過程8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析10. php網絡安全中命令執行漏洞的產生及本質探究
