一个简单的用setTimeout实现的定时器(setInerval的缺陷自行查找)
实现:
const TimeIterator = (function(){
var time = 1000
var timer = null
return function(_time, func){
time = _time || 1000
this.setTime = function(_time){ // 设置时间间隔
time = _time
},
this.startTimer = function(){ // 开启定时器
var _this = this
timer = setTimeout(function(){
func()
_this.startTimer()
},time)
},
this.stopTimer = function(){ // 停止定时器
clearTimeout(timer)
timer = null
}
}
})()
使用:
const timer = new TimeIterator(500,()=>{
console.log(1) // 希望循环的方法
})
timer.startTimer()
timer.setTime(2000)
timer.stopTimer()