Skip to content

Instantly share code, notes, and snippets.

@hugodias
Created May 8, 2013 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hugodias/5543096 to your computer and use it in GitHub Desktop.
Save hugodias/5543096 to your computer and use it in GitHub Desktop.
Set Interval with pause and resume
<script>
function RecurringTimer(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
var resume = function() {
start = new Date();
timerId = window.setTimeout(function() {
remaining = delay;
resume();
callback();
}, remaining);
};
this.resume = resume;
this.resume();
}
var timer = new RecurringTimer(function() {
document.getElementById("counter").innerHTML = ++count;
}, 1000);
var count = 0;
</script>
<input type="button" value="pause" onclick="timer.pause()">
<input type="button" value="resume" onclick="timer.resume()">
<div>Count: <b id="counter">0</b></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment