利用setTimeout实现setInterval
这里采用构造函数的方式
function SetTime(){ this.hook =true } SetTime.prototype.setIntervals = function(fn,time){ if(this.hook){ setTimeout(()=>{ fn() this.setIntervals(fn,time) },time) } } SetTime.prototype.stopInterval = function(){ this.hook = false } let time = 0 let interval = new SetTime() interval.setIntervals(function(){ console.log(time) if(time>=10){ interval.stopInterval() } time++ },100)