Last active
October 8, 2017 15:25
-
-
Save Daniel-Hug/9062765 to your computer and use it in GitHub Desktop.
chainable wrapper for JS setTimeout and setInterval
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
// call.js | |
// chainable setTimeout and setInterval JavaScript wrapper | |
// | |
// By Daniel Hug: https://gist.github.com/Daniel-Hug/9062765 | |
// MIT license: http://hug.mit-license.org/ | |
// | |
// use: | |
// var timer = call(fn, scope, args).after(1000).start(); | |
// var interval = call(fn, scope, args).every(1000).fire().start(); | |
// timer.stop(); | |
// interval.stop(); | |
function call(cb, scope, args) { | |
var t = this; | |
// automate 'new' keyword | |
if (!(t instanceof call)) return new call(cb, scope, args); | |
// set initial values | |
t.id = null; | |
t.delay = null; | |
t.going = false; | |
t.fire = function() { | |
cb.apply(scope, args); | |
return t; | |
}; | |
} | |
call.prototype = { | |
after: function(delay) { | |
var t = this; | |
t.delay = delay; | |
t.caller = function() { | |
t.going = false; | |
return t.fire(); | |
}; | |
return t; | |
}, | |
every: function(delay) { | |
var t = this; | |
t.delay = delay; | |
t.caller = function() { | |
t.fire().id = setTimeout(function() { | |
t.caller(); | |
}, delay); | |
}; | |
return t; | |
}, | |
start: function() { | |
clearTimeout(this.id); | |
this.going = true; | |
this.id = setTimeout(this.caller, this.delay); | |
return this; | |
}, | |
stop: function() { | |
clearTimeout(this.id); | |
this.going = false; | |
return this; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment