-
-
Save m4rky77/537ef736812634021158 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Runs tasks periodically. Is able to freeze when page is not active. | |
// Requires visibility.js: https://github.com/ai/visibilityjs | |
angular.module('someting', []) | |
.run(['$rootScope', function($rootScope) { | |
// wrapping visibility API into $rootScope. | |
// page becomes hidden when user switched tabs or minimized the window | |
$rootScope.pageHidden = function() { | |
return Visibility.isSupported() && Visibility.hidden(); | |
} | |
// broadcasts when visibility changes and returns true/false as message | |
// true - visible, false - invisible | |
Visibility.change(function (e, state) { | |
$rootScope.$broadcast('pageVisibilityChanged', state !== 'hidden'); | |
}); | |
}]) | |
.factory('TimerRefresher', ['$rootScope', '$timeout', | |
function($rootScope, $timeout) { | |
var TimerRefresher = function(defaultTimeout, defaultHandler) { | |
this.defaultTimeout = defaultTimeout || 5; | |
this.defaultHandler = defaultHandler; | |
var self = this; | |
// monitor page visibility changes. | |
// if page is invisible, background tasks that connect to the server | |
// stop to take load off it. | |
// if page becomes visible, the tasks are started again. | |
$rootScope.$on('pageVisibilityChanged', function(becameVisible) { | |
self.pause() | |
if (becameVisible) self.resume(); | |
}); | |
} | |
TimerRefresher.prototype.start = function() { | |
if (!this.started) { | |
this.started = true; | |
this.resume(); | |
} | |
} | |
TimerRefresher.prototype.stop = function() { | |
this.pause(); this.started = false; | |
} | |
TimerRefresher.prototype.pause = function() { $timeout.cancel(this.timer); } | |
TimerRefresher.prototype.resume = function() { | |
if (!this.started) return; | |
if ($rootScope.pageHidden()) return; | |
return this.onTimeOut(); | |
} | |
TimerRefresher.prototype.restart = function() { | |
this.stop(); this.start(); | |
} | |
TimerRefresher.prototype.onTimeOut = function() { | |
// do something... | |
if (this.defaultHandler) this.defaultHandler(); | |
// and then schedule next run | |
this.schedule(); | |
} | |
TimerRefresher.prototype.schedule = function(seconds) { | |
var self = this; | |
this.timer = $timeout(function() { self.resume(); }, (seconds || this.defaultTimeout) * 1000); | |
} | |
return TimerRefresher; | |
}]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment