小程序计时器

之前写了一个小程序倒计时的demo,在网上查看了一下,计时器很少有demo,现在来写一个。

wxml

<view class="container"> {{timecount}}</view>
<button   bindtap='start'>开始</button>
<button   bindtap='stop'>暂停</button>
<button   bindtap='Reset'>停止</button>

JS

var intt;
Page({
  data: {
    hour: 0,
    minute: 0,
    second: 0,
    millisecond: 0,
    timecount: '00:00:00',
    cost: 0,
    flag: 1,
    endtime: "",
  },
  onLoad: function () {

  },
  //开始
  start: function () {
    var that = this;
    //停止(暂停)
    clearInterval(intt);
    //时间重置
    that.setData({
      hour: 0,
      minute: 0,
      second: 0,
      millisecond: 0,
    })
    intt = setInterval(function () { that.timer() }, 50);
  },
  //暂停
  stop: function () {
    clearInterval(intt);
  },
  //停止
  Reset: function () {
    var that = this
    clearInterval(intt);
    that.setData({
      hour: 0,
      minute: 0,
      second: 0,
      millisecond: 0,
      timecount: '00:00:00',
    })
  },
  timer: function () {
    var that = this;
    console.log(that.data.millisecond)
    that.setData({
      millisecond: that.data.millisecond + 5
    })
    if (that.data.millisecond >= 100) {
      that.setData({
        millisecond: 0,
        second: that.data.second + 1
      })
    }
    if (that.data.second >= 60) {
      that.setData({
        second: 0,
        minute: that.data.minute + 1
      })
    }

    if (that.data.minute >= 60) {
      that.setData({
        minute: 0,
        hour: that.data.hour + 1
      })
    }
    that.setData({
      timecount: that.data.hour + ":" + that.data.minute + ":" + that.data.second + ":" + that.data.millisecond
    })
  },
});

css:

.container{
  height:200rpx;
  line-height:200rpx;
  font-size:50rpx;
}

button{
  width:150rpx;
  background: rgb(7, 193, 96);
  color: #fff;
  margin-bottom: 8px;
}

要是样式css不想写了,可以用组件库, 如果组件库不会使用,可以查看教程 五分钟上手-微信小程序组件库 iView Weapp https://www.jianshu.com/p/09b4515152ff

效果:

原文作者:祈澈姑娘 技术博客:https://www.jianshu.com/u/05f416aefbe1 90后前端妹子,爱编程,爱运营,文艺与代码齐飞,魅力与智慧共存的程序媛一枚。 欢迎关注【编程微刊】公众号,回复【领取资源】,500G编程学习资源干货免费送。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券