KingKongFrog
KingKongFrog

Reputation: 14419

angular.js run code ONLY if window is in focus

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

Upvotes: 0

Views: 1510

Answers (3)

Peter
Peter

Reputation: 14508

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.

Upvotes: 0

Kevin Hakanson
Kevin Hakanson

Reputation: 42210

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

});

Upvotes: 1

Mikko Viitala
Mikko Viitala

Reputation: 8404

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

Upvotes: 1

Related Questions