vue實(shí)現(xiàn)簡易計(jì)時器組件
在做項(xiàng)目中難免會碰到需要實(shí)時刷新,廣告動畫依次出現(xiàn)等等需求,剛最近基于業(yè)務(wù)需求,需要實(shí)現(xiàn)一個累加通話時長的計(jì)時器,這時候就需要定時器登上我們的代碼舞臺了,其實(shí)對于計(jì)時器,它的原理就是通過定時器來實(shí)現(xiàn)的,那么在寫業(yè)務(wù)需求之前,我先說說關(guān)于定時器的一些知識。
window對象提供了兩個方法來實(shí)現(xiàn)定時器的效果,分別是window.setTimeout()和window.setInterval。
在Javascript中,代碼一般都是同步執(zhí)行的,但定時器卻是異步執(zhí)行的。
window.setTimeout(callback,delay); //callback:回調(diào)函數(shù) delay:時間間隔時長window.setInterval(callback,delay);
定時器分為隔時定時器setInterval和延時定時器setTimeout
那么它們兩到底有什么區(qū)別呢?
setInterval以指定時間為周期循環(huán)執(zhí)行,一般用于刷新表單、復(fù)雜動畫的循環(huán)執(zhí)行,對于一些表單的實(shí)時指定時間刷新同步 setTimeout只在指定時間后執(zhí)行一次,像有些網(wǎng)站剛進(jìn)去會出現(xiàn)一個彈窗廣告,一般都是用的setTimeout了解了定時器的基本知識之后,那么接下來就可以進(jìn)行功能的實(shí)現(xiàn)了。
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 () { //建議開啟定時器前,先清除定時器,避免定時器累加,出現(xiàn)不可預(yù)期的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>
這樣,一個簡單的計(jì)時器組件就實(shí)現(xiàn)好了,其實(shí)還有其他的實(shí)現(xiàn)思路,如果以后開發(fā)碰到了類似的需求,可以借鑒,希望對你們有所幫助。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享2. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法3. ASP中if語句、select 、while循環(huán)的使用方法4. xml中的空格之完全解說5. WMLScript的語法基礎(chǔ)6. 匹配模式 - XSL教程 - 47. XML入門的常見問題(四)8. ASP中解決“對象關(guān)閉時,不允許操作。”的詭異問題……9. html小技巧之td,div標(biāo)簽里內(nèi)容不換行10. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯誤頁的問題
