Skip to content

Instantly share code, notes, and snippets.

@nylki
Forked from ncou/interval.js
Created June 15, 2020 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nylki/a13d5e40c6c213265e8680f3c04822f6 to your computer and use it in GitHub Desktop.
Save nylki/a13d5e40c6c213265e8680f3c04822f6 to your computer and use it in GitHub Desktop.
setTimeout and setInterval with pause and resume
// http://stackoverflow.com/questions/7279567/how-do-i-pause-a-window-setinterval-in-javascript
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();
}
function Timer(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = function() {
start = new Date();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
}
var timer = new Timer(function() {
alert("Done!");
}, 1000);
timer.pause();
// Do some stuff...
timer.resume();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment