Last active
August 29, 2015 14:16
-
-
Save dfkaye/a1597ff98739c2e80af1 to your computer and use it in GitHub Desktop.
pretty simple on-off interface for continuously running a function over a given interval (if specified)
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
/* | |
answer for Tim Evko @tevko re https://twitter.com/Tevko/status/572698827548839936 | |
March 3, 2015 | |
continuous() | |
+ calls a function fn continuously every (optional) interval milliseconds | |
+ provides on-off or pause-resume switch | |
*/ | |
function continuous(fn, interval) { | |
// The strategy is to create a middleman function that | |
// + holds on to the runnable {fn} function via closure | |
// + returns itself as the API with on and off methods. | |
typeof interval != 'number' && (interval = 0); | |
var runnable = fn; | |
var timeout; // or requestID | |
// when fn is a function it will be called repeatedly | |
// until middle.off(); is called | |
function middle(fn) { | |
runnable = fn; | |
timeout = window.clearTimeout(timeout); // or cancelAnimationFrame(requestID) | |
// if runnable is callable... | |
typeof runnable == 'function' && | |
(timeout = window.setTimeout(function run() { // or requestID = requestAnimationFrame(function run...) | |
runnable(); // runnable wraps whatever real logic we want | |
middle.on(); // ready for next | |
}, interval)); | |
return middle; | |
} | |
// resume | |
middle.on = function on() { | |
//console.log('on'); | |
return middle(fn); | |
} | |
// pause | |
middle.off = function off() { | |
console.log('off'); | |
return middle(null); | |
} | |
return middle; | |
} | |
/***** test *****/ | |
// this wraps whatever logic you'd really want to execute | |
function runnable () { | |
console.log('running'); | |
} | |
// optional call interval (defaults to 0 in continuous()) | |
var interval = 50; | |
// create continuous instance | |
var m = continuous(runnable, interval); | |
// start calling runnable continuously untile we call m.off(); | |
m.on(); | |
// demonstrate on-off switch using planned timeouts | |
setTimeout(m.off, 250); | |
setTimeout(m.on, 500); | |
setTimeout(m.off, 750); | |
/* | |
should see: | |
running | |
running | |
running | |
running | |
off | |
running | |
running | |
running | |
running | |
off | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment