简单原生js基于window对象的倒计时任务对象

/**
*
* @param {Number} time 任务倒计时时间
* @param {Function} callback 回调方法
*/
const countdown = function (time, callback){
/**
* 执行时间
* @type {number}
*/
this.time = time ? time : 120
/**
* 默认任务时间
* @type {number}
*/
this.defaultTime = time ? time : 120
/**
* 任务Id
* @type {Number}
*/
this.id = null
/**
* 回调函数
* @type {Function}
*/
this.callback = callback
/**
* 倒计时完成标识,false未完成,true已完成
* @type {boolean}
*/
this.completeFlag = false
/**
* 倒计时任务进行状态,false为执行,true执行中
* @type {boolean}
*/
this.status = false

/**
* 取消定时任务
*/
this.cancel = function (){
this.status = false
window.clearInterval(this.id)
}

/**
* 暂停或开启定时任务
*/
this.pause = function (){
if (this.status){
this.cancel()
}else {
if (this.time > 0){
this.start()
}
}
}

/**
* 执行倒计时任务
*/
this.start = function (){
this.completeFlag = false
this.status = true
let self = this
if (self.time <= 0){
return
}
this.id = window.setInterval(function (){
self.time--
if (self.time <= 0) {
self.completeFlag = true
self.status = false
window.clearInterval(self.id)
if (self.callback && typeof self.callback === 'function'){
self.callback()
}
}
}, 1000)
return self.id
}

/**
* 重新开始新一轮的计时
*/
this.restart = function (){
this.time = this.defaultTime
if (!this.completeFlag || this.status){
this.cancel()
}
this.start()
}
}

posted @ 2022-03-23 16:18  SurfingCat  阅读(52)  评论(0编辑  收藏  举报