Skip to content

Instantly share code, notes, and snippets.

@nathan-osman
Created October 19, 2015 21:28
Show Gist options
  • Save nathan-osman/f03d899d2254c98e31a1 to your computer and use it in GitHub Desktop.
Save nathan-osman/f03d899d2254c98e31a1 to your computer and use it in GitHub Desktop.
Simple class for managing timeouts in JavaScript
/**
* Simplify the process of setting and resetting timeouts.
* @param fn callback to invoke
* @param delay time in MS
*
* Any additional parameters are passed to the callback when invoked.
*/
function Timeout(fn, delay) {
var timeout = null,
args = $.map(arguments, function(v, i) {
if(i > 1) {
return v;
}
});
/**
* Determine if the timeout is active.
*/
var isActive = this.isActive = function() {
return timeout !== null;
};
/**
* Cancel the timeout.
*/
var stop = this.stop = function() {
if(isActive()) {
window.clearTimeout(timeout);
timeout = null;
}
};
/**
* Immediately run the callback and cancel the timeout.
*/
var run = this.run = function() {
stop();
fn.apply(null, args);
};
/**
* Start the timer or restart it if it is already running.
*/
this.start = function() {
stop();
timeout = window.setTimeout(function() {
timeout = null;
run();
}, delay);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment