Created
August 21, 2014 17:44
-
-
Save vermilion1/f6cb5ec731a6bee95b20 to your computer and use it in GitHub Desktop.
Advanced timer with ability to pause/resume the callback
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
/** | |
* 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