[英]Call and stop a rest service with an interval of time
I need to make a rest call every x interval seconds (3000 ms) to consult the status of a webservice until i have the wanted result or until 12 times (for example) or when I receive the status expected: 我需要每隔x间隔秒(3000毫秒)进行一次休息呼叫,以查询Web服务的状态,直到获得所需结果或直到12次(例如)或收到预期状态为止:
function myFunction() {
var i=0;
var _onSuccess = function(response) {
if (response.status=== 'READY' || i >= 12) {
clearInterval(x);
if(response.status !== 'READY') {
$location.path('/errorView');
}
}
}
var x = setInterval(function () {
$rest.getSomething(_onSuccess)
}, 3000);
}
I have another function that calls myFunction with a timeout because if I dont receive the expected result after 32 seconds i want to cancel stop rest call and go to an error view. 我有另一个函数,该函数以超时方式调用myFunction,因为如果32秒钟后仍未收到预期的结果,我想取消stop rest调用并转到错误视图。
function myFunction2() {
myFunction();
$timeout(function () {
$location.path('/routeWhenStatusReady');
}, 32000);
}
Is there any way to improve this? 有什么办法可以改善这一点? I want to finish timeout myFunction2 if the Ready status is ok in 16 seconds for example and not to wait 32 seconds... 如果要在16秒钟之内准备就绪状态正常,我想完成myFunction2的超时,而不要等待32秒...
Thank you! 谢谢!
You could set the $timeout in a variable: 您可以在变量中设置$ timeout:
var myTimeout = $timeout
and finish it with: 并完成以下步骤:
$timeout.cancel(myTimeout);
Store the $timeout
timer in a global scope which can be accessed by myFunction
. 将$timeout
计时器存储在可以由myFunction
访问的全局范围内。 And cancel the timer when you reach your desired result. 并在达到所需结果时取消计时器。
var timer=null;
function myFunction(){
var i=0;
var _onSuccess = function(response){
if (response.status=== 'READY' || i >= 12) {
clearInterval(x);
if(timer){
$timeout.cancel(timer);
}
if(response.status !== 'READY'){
$location.path('/errorView');
}
}
}
var x = setInterval(function () {
$rest.getSomething(_onSuccess)
}, 3000);
}
function myFunction2(){
myFunction();
timer = $timeout(function () {
$location.path('/routeWhenStatusReady');
}, 32000);
}
step 1 : 第1步 :
assign $interval to a variable 将$ interval分配给变量
var timeHandler = $interval(() => {
// your code
}, 1000) };
step 2: 第2步:
and cancel it when ever you want by passing variable in interval cancel function 并在间隔取消函数中传递变量以在需要时取消它
$interval.cancel(timeHandler);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.