通常做法是拿一個計數器,到了就停止。
// 執行60次後結束
var timesRun = 0;
var interval = setInterval(function(){
timesRun += 1;
if(timesRun === 60){
clearInterval(interval);
}
//do whatever here..
}, 2000);
引用自:https://blog.csdn.net/chelen_jak/article/details/82899153
更加友善的做法:
// 這種方法簡單優雅,不影響原來的流程
const interval = setInterval(function(){
//do whatever here..
}, 1000);
// 10次後結束,因為一般都知道每次間隔是多少,那10次後就是:10000。
setTimeout(() => {
clearInterval(interval )
}, 10000);
如果有rxjs,那就更加優雅了:
就一行代碼,效果跟上面的代碼一樣,是不是很清爽
// 就一行代碼,效果跟上面的代碼一樣,是不是很清爽
Rx.Observable.interval(1000).take(10).subscribe(() => {console.log("hello rxjs")});