Skip to content

Instantly share code, notes, and snippets.

@m4rky77
Forked from theorm/TimerRefresher.js
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m4rky77/537ef736812634021158 to your computer and use it in GitHub Desktop.
Save m4rky77/537ef736812634021158 to your computer and use it in GitHub Desktop.
// 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