2017-04-21 39 views
0

只有在瀏覽器中打開當前選項卡時,纔會每2秒調用一次角度js函數。有什麼方法可以檢查當前頁面是否在瀏覽器中處於活動狀態。只有在瀏覽器中當前選項卡處於活動狀態時才執行角度函數

$scope.callAtInterval = function() { 

     var url = "http://127.0.0.1/test"; 

     $http.get(url).success(function(response) { 
      $scope.initial = response; 

     }, 
     function errorCallback(response) { 
      $scope.result=response; 
         }); 
} 

$interval(function(){ $scope.callAtInterval(); }, 5000); 

}

+0

發佈您的代碼! –

+0

@sachila ranawaka我發佈了代碼。在這裏,每5秒將會進行api調用,數據將被更新。但是我只想在瀏覽器中激活當前選項卡時才這樣做。 –

+0

也顯示html代碼 –

回答

0

你會使用對焦和模糊窗口的事件:

$(window).on("blur focus", function(e) { 
    var prevType = $(this).data("prevType"); 

    if (prevType != e.type) { // reduce double fire issues 
     switch (e.type) { 
      case "blur": 
       // cancel your interval function 
       break; 
      case "focus": 
       // emit your interval function 
       break; 
     } 
    } 

    $(this).data("prevType", e.type); 
}) 
相關問題