//定时任务 function Task(cnt, timeout, run) { function newInterval() { return window.setInterval(function () { if(i < cnt){ try { run(i); } catch (e) { console.error(e); } } else { window.clearInterval(interval); } i++; },timeout); } var i = 0, interval; return { //如果已经在执行,则重新开始 start: function () { if(interval){window.clearInterval(interval);} i = 0; interval = newInterval(); } //中断任务 , close: function () { if(interval){window.clearInterval(interval); delete interval;} } } } //循环执行10次,每次等待1秒 var task = new Task(10, 1000, function (i) { console.log(i); })