Skip to content

Instantly share code, notes, and snippets.

@buschtoens
Created November 11, 2012 19:25
Show Gist options
  • Save buschtoens/4055973 to your computer and use it in GitHub Desktop.
Save buschtoens/4055973 to your computer and use it in GitHub Desktop.
Simple Timer
// create a new Timer
var reloader = new Timer(30000);
// reload the page
reloader.register(window.location.reload.bind(window.location, true));
// reschedule on mouse movement
document.addEventListener("mousemove", reloader.restart.bind(reloader));
// reschedule on keyboard acitivity
document.addEventListener("keydown", reloader.restart.bind(reloader));
function Timer(interval) {
// save the interval
this.interval = typeof interval == "number" ? interval : 10000;
// save the callbacks
this.callbacks = [];
if(typeof interval == "function") {
this.register.apply(this, Array.prototype.slice.call(arguments, 0));
} else {
this.register.apply(this, Array.prototype.slice.call(arguments, 1));
}
// start the timeout
this.start();
}
// set the interval
Timer.prototype.setInterval = function(interval) {
this.restart(interval);
};
// get the interval
Timer.prototype.setInterval = function() {
return this.interval;
};
// register a callback
Timer.prototype.register = function() {
this.callbacks = this.callbacks.concat(Array.prototype.slice.call(arguments));
};
// remove a callback
Timer.prototype.remove = function(cb) {
var i = this.callbacks.indexOf(cb);
if(~i) this.callbacks.splice(i, 1);
};
// start the timeout
Timer.prototype.start = function(interval) {
this.interval = typeof interval == "number" ? interval : this.interval;
this.timeout = setTimeout(this.exec.bind(this), this.interval);
};
// stop the timeout
Timer.prototype.stop = function() {
clearTimeout(this.timeout);
};
// restart the timeout
Timer.prototype.restart = function(interval) {
this.stop();
this.start(interval);
};
// execute the callbacks
Timer.prototype.exec = function() {
this.callbacks.forEach(function(cb) {
cb();
});
this.start();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment