Skip to content

Instantly share code, notes, and snippets.

@krambuhl
Last active August 29, 2015 13:57
Show Gist options
  • Save krambuhl/9578438 to your computer and use it in GitHub Desktop.
Save krambuhl/9578438 to your computer and use it in GitHub Desktop.
A set of underscore mixins for timer functions.
_.mixin({
bindDelay: function(func, context, wait) {
return _.delay(_.bind(func, context || this), wait, _.last(arguments, 3));
},
bindDefer: function(func, context) {
return _.defer(_.bind(func, context || this), _.last(arguments, 2));
},
repeat: function(func, interval) {
var args = _.last(arguments, 2);
return setInterval(_.bind(func, null, args), interval);
},
repeatForDuration: function(func, interval, duration) {
duration = duration || 500;
interval = interval || (1000 / 60);
var args = _.last(arguments, 3),
timer = setInterval(_.bind(func, null, args), interval);
_.delay(function() {
if (duration % interval == 0) func.apply(null, args);
clearTimeout(timer);
}, duration);
return timer;
}
});
@krambuhl
Copy link
Author

repeatForDuration will repeat a function on an interval and stop after a defined duration.

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