Skip to content

Instantly share code, notes, and snippets.

@jpehman
Last active March 14, 2017 18:38
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 jpehman/09922ceec9798bcde3748da84fa64868 to your computer and use it in GitHub Desktop.
Save jpehman/09922ceec9798bcde3748da84fa64868 to your computer and use it in GitHub Desktop.
(function () {
"use strict";
function timeout (callback, duration) {
var startTime = null, pauseTime = null,
remainingTime = 0,
timer = null;
repeating = repeating || false;
callback = callback || function () {};
if (typeof duration !== "number") {
throw new TypeError("duration must be a number", "function timeout", 10);
}
else if (duration < 0) {
throw new Error("duration must be 0 or greater", "fuction timeout", 13);
}
remainingTime = duration;
var start = function () {
timer = setTimeout(callback, remainingTime);
startTime = new Date();
},
clear = function () {
clearTimeout(timer);
timer = null;
},
pause = function () {
if (timer === null) {
return;
}
pauseTime = new Date();
clear();
},
resume = function () {
if (timer !== null) {
return;
}
remainingTime -= pauseTime.getTime() - startTime.getTime();
if (remainingTime) {
start();
}
},
stop = function () {
if (timer === null) {
return;
}
remainingTime = duration;
clear();
};
start();
return {
"start": start,
"pause": pause,
"resume": resume,
"stop": stop
}
}
window.timeout = timeout;
}());
@jpehman
Copy link
Author

jpehman commented Mar 10, 2017

A simple timeout function that can be paused, resumed, stopped, and started again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment