我有一个每5秒运行一次的setInterval函数。我希望该函数内的代码仅在窗口为infocus时才运行。我已经尝试了,但它似乎没有用。
$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);
答案 0 :(得分:1)
我认为你正在寻找angular $window
包装器,在函数外定义isonfocus
也会有很大的帮助。
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);
});
答案 1 :(得分:1)
使用Page Visibility API和响应事件而不是轮询会更好吗?
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
});