当前位置: 首页 > 工具软件 > App-Countdown > 使用案例 >

uni-app - javaScript - vue2 计时器(倒计时和正计时)

淳于兴朝
2023-12-01

正计时 

1.在data里面定义

     data() {
			return {
				time: '00:00:00',
				timer: '',
				hour: 0,
				minutes: 0,
				seconds: 0
			}
		},

2.页面按钮

<template>
	<view>
		<button @click="begin">开始计时{{time}}</button>
		<button @click="pause">暂停</button>
	</view>
</template>

3.开始计时

           // 开始计时
			begin() {
				this.timer = setInterval(this.startTimer, 1000);
			},
			startTimer() {
				this.seconds += 1;
				if (this.seconds >= 60) {
					this.seconds = 0;
					this.minutes = this.minute + 1;
				}
				if (this.minutes >= 60) {
					this.minutes = 0;
					this.hour = this.hour + 1;
				}
				this.time = (this.hour < 10 ? '0' + this.hour : this.hour) + ':' + (this.minutes < 10 ? '0' + this
					.minutes :
					this.minutes) + ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds);
			},

4.暂停计时

//暂停计时
	pause() {
		if (this.timer) {
			clearInterval(this.timer);
		}
	},

倒计时

1.在data里面定义

     data() {
			return {
				timer: '',
				examtime: 1000, //
			}
		},

2.页面显示

<template>
	<view>
		倒计时:{{examtime}}
	</view>
</template>

3.调用及方法编写

        onLoad() {
			this.timer = setInterval(this.countDown, 1000) //毫秒 1秒
		},

		methods: {
			//倒计时
			countDown() {
				var a = this.examtime--
				if (a == 0) {
					this.examtime = 0
					clearInterval(this.timer)
					this.show = true
				}
			},
		}

离开页面记得清除定时器

destroyed() {
            clearInterval(this.timer);
        },

 类似资料: