js 计时器 核心代码

小程序定时器代码示例

下面是一个简单的例子,,后面显示最核心的代码片段

// components/countDown/countDown.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    startTime: {
      type: String,
      value: ''
    },
    endTime: {
      type: String,
      value: ''
    }
  },

  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      // console.log(this.data)

      let now = new Date().valueOf() / 1000;
      let start = new Date(this.properties.startTime).valueOf() / 1000;
      let end = new Date(this.properties.endTime).valueOf() / 1000;

      this.setData({
        Maintain_time: now < start ? (start - now) : (now < end ? end - now : 0)
      })
      if (now > start) {
        this.setData({
          display: 1
        })
      }

      this.mytime();

    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
      this.destroyed();
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    TIME: "0天0时0分0秒", //用于显示的值

    display: 0,

    d: '0',
    h: '00',
    m: '00',
    s: '00',


    Maintain_time: '', // 用于实际计算使用的倒计时
    t: "", //定时器富于的变量。关闭页面要销毁,

  },

  /**
   * 组件的方法列表
   */
  methods: {

    mytime: function () {
      let that = this;
      // this.setData({
      setInterval(this.countTime, 1000, that)
      // })
    },

    countTime: function (that) {
      // console.log(that);
      let time = that.data.Maintain_time;
      // console.log(time)
      if (time > 0) {
        let d, h, m, s;
        d = parseInt(time / 60 / 60 / 24);
        h = parseInt((time / 60 / 60) % 24);
        m = parseInt((time / 60) % 60);
        s = parseInt(time % 60);
        // console.log(d, h, m, s);

        let tmpTime = (that.data.Maintain_time) - 1;
        // console.log(tmpTime);
        that.setData({
          Maintain_time: tmpTime,
          d: (d.toString().length == 1 ? '0' + d : d),
          h: (h.toString().length == 1 ? '0' + h : h),
          m: (m.toString().length == 1 ? '0' + m : m),
          s: (s.toString().length == 1 ? '0' + s : s),
        })
      }
    },


    destroyed() {
      clearInterval(this.data.t);
    },



  }
})

核心代码
//time 秒 是毫秒级别/1000 正确的时间戳格式 可以使用 ValueOf()进行转换


		d = parseInt(time / 60 / 60 / 24);
        h = parseInt((time / 60 / 60) % 24);
        m = parseInt((time / 60) % 60);
        s = parseInt(time % 60);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值