关于uni-app 倒计时 清除、熄屏等问题

息屏:通过一行代码plus.device.setWakelock(true);来实现,设置让屏幕长亮。
倒计时:需要设置一个变量,通过setInterval函数来实时更新,注意:当返回上一页或者倒计时结束要 清除倒计时,否则会影响后面代码,已实测。

<template>
	<view>
			<text style="color: #E60000;">倒计时:{
   
   {interval}}</text>
	</view>
</template>	
<script>
  let maxtime = 0
	export default {
		data() {
			return {
				interval: '',
		        timer: null,
		        estimateTime: 0,
			}
		},
		onLoad(option) {
		      // 设置让屏幕长亮
		      plus.device.setWakelock(true);
		       maxtime = this.estimateTime * 60
		       // 很重要
		        this.timer = setInterval(() => {
		         	  this.countDown()
		      }, 1000)
		},	
		// 点击 返回 上一页
		onBackPress(e) {
		      if (e.from === 'backbutton' ) {
		        uni.showModal({
		          title: '提示',
		          content: '放弃本次考试,结束本次考试流程,是否结束?',
		          success: res => {
		            if (res.confirm) { 
		               // 清除倒计时
		              clearInterval(this.timer)
		              this.finishExam()
		            } else if (res.cancel) {
		            }
		          }
		        })
		        return true;
		      }
		 },
		methods: {
		  countDown: function () {
		    if (maxtime >= 0) {
			      let minutes = Math.floor(maxtime / 60) < 10 ? '0'+Math.floor(maxtime / 60) : Math.floor(maxtime / 60),
	              seconds = Math.floor(maxtime % 60) < 10 ? '0'+Math.floor(maxtime % 60) : Math.floor(maxtime % 60);
		          this.interval = `${minutes}:${seconds}`
		          maxtime = maxtime - 1;
	        } else {
			      clearInterval(this.timer)
		          uni.showModal({
		            title: '提示',
		            content: '倒计时结束!',
		            success: res => {
		              if (res.confirm) {
		                // 调接口
		                this.finishExam()
		              } else if (res.cancel) {
		                // 调接口
		                this.finishExam()
		              }
		            }
	          })
	       }   
        }
      },
</script>		

猜你喜欢

转载自blog.csdn.net/qq_45511353/article/details/110805353