Skip to content

Instantly share code, notes, and snippets.

@drch-
Created April 12, 2012 16:15
Show Gist options
  • Save drch-/2368748 to your computer and use it in GitHub Desktop.
Save drch-/2368748 to your computer and use it in GitHub Desktop.
misc js utils
util = {
//calls a func every [timeout] ms for [stopMillis] ms.
//returns a jQuery.Promise
every: function (func, timeout, stopMillis, callnow) {
function _every(func, timeout, absoluteStop, deferred) {
if (new Date().getTime() >= absoluteStop) {
deferred.resolve();
return;
}
func();
_.delay(function () { _every(func, timeout, absoluteStop, deferred); }, timeout);
}
var deferred = $.Deferred(),
absoluteStop = new Date().getTime() + stopMillis,
firstCall = function () { _every(func, timeout, absoluteStop, deferred); };
callnow ? firstCall() : _.delay(firstCall, timeout);
return deferred.promise();
},
//calls a func [times] times with a [timeout]ms delay
//returns a jQuery.Promise
times: function (func, timeout, times, callnow) {
function _times(func, timeout, times, deferred) {
if (times == 0) {
deferred.resolve();
return;
}
func();
_delay(function () { _times(func, timeout, times - 1, deferred); }, timeout);
}
var deferred = $.Deferred(),
firstCall = function () { _times(func, timeout, times, deferred); };
callnow ? firstCall() : _.delay(firstCall, timeout);
return deferred.promise();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment