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

正计时 

1.在data里面定义

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

2.页面按钮

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.页面显示

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

你可能感兴趣的:(uni-app,vue.js,javascript)