Skip to content

Instantly share code, notes, and snippets.

@vermilion1
Created August 21, 2014 17:44
Show Gist options
  • Save vermilion1/f6cb5ec731a6bee95b20 to your computer and use it in GitHub Desktop.
Save vermilion1/f6cb5ec731a6bee95b20 to your computer and use it in GitHub Desktop.
Advanced timer with ability to pause/resume the callback
/**
* Advanced timer with ability to pause/resume the callback.
* @param {function} callback - Callback to be executed after some delay.
* @param {number} delay - Delay.
* @returns {Object} Timer object with useful methods.
*/
var timer = function (callback, delay) {
var isPaused = true;
var timer, start, clear, pause, resume;
clear = function () {
isPaused = false;
clearTimeout(timer);
};
resume = function () {
clear();
isPaused = false;
start = new Date();
if (delay >= 0) {
timer = setTimeout(callback, delay);
}
};
pause = function() {
clear();
isPaused = true;
delay -= new Date() - start;
};
return {
clear: clear,
resume: resume,
pause: pause,
isPaused: function() {
return isPaused;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment