$timeout和$interval如何在角度中协同工作



我是角度新手,我想以 3 秒的间隔调用一个函数 doSomething(( 15 秒。 doSomething(( 在内部调用一个 REST API,我想每 3 秒调用一次该 API。

我想在 15 秒后停止该 API 调用。

如何通过$timeout和$interval功能做到这一点?

您只能通过$timeout来执行此操作:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope,$timeout) {
var count = 0;
callApi();
function callApi() {
$timeout(function () {
if(count < 5) {
count++;
callApi(); // call this function again
console.log("this is"+count+"th loop");
}
}, 3000);
}
});

也许你可以使用超时和for循环来实现这一点

var pull;
function timeOut(i){
pull = $timeout(function () {
console.log("put your req "+1)
},3000)
}
for(var i=0; i<5; i++){
timeOut(i)
}

执行完成后,您可以取消超时

$scope.$on('$destroy', function(){
$timeout.cancel(pull);
});

在这里使用$interval更清楚

var intervalTimeSec = 3;
var intervalTimeLimitSec = 15;
var apiCalls = 0;
var intervalId = $interval(function() {
//call the API here
apiCalls++;
if (apiCalls * intevalTimeSec >= intervalTimeLimitSec) {
$interval.cancel(intervalId); // stops the interval
}
}, intervalTimeSec * 1000)

最新更新