Last active
March 14, 2017 18:38
-
-
Save jpehman/09922ceec9798bcde3748da84fa64868 to your computer and use it in GitHub Desktop.
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
(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; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple timeout function that can be paused, resumed, stopped, and started again.