方法一:
function SetInterval(fun, sec){
function recFun(){
fun();
this.id = setTimeout(recFun, sec);//将任务的标识符记录在timer对象中
}
this.stop = function(){
clearTimeout(this.id);//取消下一个任务的执行
}
this.start = function(){
if(typeof this.id === "undefined"){
recFun = recFun.bind(this); //将递归函数的this引用和当前对象即timer绑定
recFun();
}
}
}
/*测试*/
var timer = new SetInterval(() => console.log("?"), 1000);
timer.start();
setTimeout(() => timer.stop(), 5000);
方法二:
function setInter(opFun,n=0,du,stopNum) {
setTimeout(function fn (){
n+=1
opFun()
if(n<stopNum){
setTimeout(fn, du);
}
},du)
}
let one = 1
setInter(0,()=> {one+=1;console.log(one)},1000,15)