微信小程序: 计时功能

利用 setInterval() 函数来实现长时间计时的功能。

使用 clearInterval() 函数来清除计时器

步骤如下:

1. 在需要计时的页面或组件中定义一个计时器变量,如 `timer`,并初始化为 0。

2. 使用 `setInterval()` 函数,在一段时间间隔内执行一次指定的函数,并将返回值赋给计时器变量

timer = setInterval(function() {
// todo编写计时器的逻辑
}, 1000);

3. 在计时器函数中编写计时器的逻辑

var second = 0; // 定义一个秒数变量
 function timerFunction() {
   second++; // 每秒钟秒数加一
 }

4. 当需要停止计时器时,可以使用 `clearInterval()` 函数来清除计时器


如:clearInterval(timer); // 停止计时器

代码记录:

js页面

Page({
  data:{
   timer2: null,
   nowTime: '00:00:00', // 计时
   hour: 0,
   minutes: 0,
   seconds: 0
  },
  onLoad() {
    // 开始计时
    if (this.timer2) {
      clearInterval(this.timer2)
    }
    this.timer2 = setInterval(this.startTimer, 1000)
  },
   onHide() {
    clearInterval(this.timer2) // 清空计时器
    this.setData({
      nowTime: '00:00:00', // 计时
      hour: 0,
      minutes: 0,
      seconds: 0
    })
  },
  // 开启定时器
  startTimer() {
    this.data.seconds += 1
    if (this.data.seconds >= 60) {
      this.setData({
        seconds: 0,
        minutes: this.data.minutes + 1
      })
    }
    if (this.data.minutes >= 60) {
      this.setData({
        minutes: 0,
        hour: this.data.hour + 1
      })
    }
    this.setData({
      nowTime: `${this.toZero(this.data.hour) + ':' + this.toZero(this.data.minutes) + ':' + this.toZero(this.data.seconds)}`
    })
  },
  // 添0 
  toZero(timeNumber) {
    return timeNumber < 10 ? '0' + timeNumber : timeNumber
  },
})

wxml页面

<view class="bg-time">
    {{nowTime}}
  </view>

效果

 

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值