angular.js run code ONLY if window is in focus

1.4k views Asked by At

I have a setInterval function that runs every 5 seconds. I want the code inside that function to only run if the window is infocus. I've tried but it doesnt seem to work.

$scope.myFunction = function() {
  var isonfocus = true;  

  window.onblur = function() {  
    isonfocus = false;  
  }  

  window.onfocus = function() {  
    isonfocus = true;  
  }

  if (isonfocus) {   
    console.log("focused!");
  }
}

setInterval(function() {
  $scope.myFunction();
}, 5000);
3

There are 3 answers

0
Mikko Viitala On

I think you are looking for angular's $window wrapper and defining isonfocus outside the function would help a lot, too.

app.controller('Ctrl', function($scope, $window) {
  var hasFocus;

  $scope.myFunction = function() {
    $window.onblur = function() {  
      console.log('>onblur');
      hasFocus = false;  
    };  

    $window.onfocus = function() {  
      console.log('>onfocus');
      hasFocus = true;  
    };

    console.log(hasFocus ? 'focused' : 'not focused');
  };

  setInterval(function() { // or $interval
    $scope.myFunction();
  }, 5000);
});
0
Kevin Hakanson On

Would this work better with the Page Visibility API and by responding to events instead of polling?

app.run(['$rootScope', '$document', function ($rootScope, $document) {
    $document.on('visibilitychange', function () {
        $rootScope.$broadcast('visibilityChange', document.hidden, document.visibilityState);
    });
}]);

// in controller
$scope.$on('visibilityChange', function (event, hidden, visibilityState) {
    // respond to event

});
0
Peter On

You realise that you're reassigning the event handler on every iteration right? Move the onblur and onfocus eventhandler outside of your $scope.myFunction and try this again.