一个简单定时器的js部分

281 阅读1分钟

实现简单的倒计时读秒功能,废话不说,直接上代码:

Page({
    data: {
        item: [{
            title: '小麦教育开学季送福利!精品体验课组团仅需9.9元!',
            content: '',
            deadline: "2020-07-01"
        }, {
            title: '小麦教育开学季送福利!',
            content: '',
            deadline: "2020-07-01"
        }],
    },

    onLoad: function(options) {
        this.startCountDown()
    },

    timeDifference: function() {
        let that = this
        this.data.item.forEach(function(item, index, array) {
            let today = new Date()
            let deadline = new Date(item.deadline)
            let time = deadline.getTime() - today.getTime() //时间差
            let days = Math.floor(time / (24 * 3600 * 1000)) //天数
            time = time % (24 * 3600 * 1000)
            let hours = Math.floor(time / (3600 * 1000)) //小时数
            time = time % (3600 * 1000)
            let minutes = Math.floor(time / (60 * 1000)) //分钟数
            time = time % (60 * 1000)
            let seconds = Math.floor(time / 1000) //秒数
            let str = `${days}${hours}小时${minutes}${seconds}秒`
            that.setData({
                [`item[${index}].content`]: `还剩:${str}`
            })
        });
    },

    startCountDown: function() {
        let that = this
        setTimeout(function() {
            that.timeDifference()
            that.startCountDown()
        }, 1000)
    }
})