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

正计时 

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.minutes + 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);
        },

  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值