2017-07-06 75 views
1

我需要每隔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); 
} 

我有一個超時調用myFunction的另一個功能,因爲如果我不獲得32秒後,我想取消停止REST調用,去一個錯誤觀點預期的結果。

function myFunction2() { 
    myFunction(); 
    $timeout(function() { 
     $location.path('/routeWhenStatusReady'); 
    }, 32000); 
} 

有什麼辦法可以改善嗎?我想完成超時myFunction2,如果就緒狀態在16秒內完好,例如不等待32秒...

謝謝!

回答

0

你可以設置$超時在一個變量:

var myTimeout = $timeout

,並完成它:

$timeout.cancel(myTimeout);

0

商店$timeout計時器在全球範圍內,可以通過訪問myFunction。當你達到你想要的結果時取消計時器。

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); 
    } 
0

第1步:

分配$間隔可變

var timeHandler = $interval(() => { 
       // your code 
}, 1000) }; 

第2步:

,並取消它時,任何你想傳遞變量在間隔取消功能重刑

$interval.cancel(timeHandler); 

Refrence:here