add Ox.throttle and Ox.debounce

This commit is contained in:
j 2014-02-02 01:15:17 +05:30
parent 0df1056d3f
commit 92a122eb0a

View file

@ -147,6 +147,62 @@ Ox.queue = function(fn, maxThreads) {
return ret; return ret;
}; };
/*@
Ox.throttle <f> Runs a function at most once per given time frame
(fn[, ms]) -> <f> Throttled function
fn <f> Function to throttle
ms <n|250> Interval in milliseconds
@*/
Ox.throttle = function(fn, ms) {
var args,
timeout;
ms = arguments.length == 1 ? 250 : ms;
return function() {
args = arguments;
if (!timeout) {
fn.apply(null, args);
args = null;
timeout = setTimeout(function() {
if (args !== null) {
fn.apply(null, args);
}
timeout = null;
}, ms);
};
};
};
/*@
Ox.debounce <f> Runs a function once it stops being called for a given time frame
(fn[, ms][, immediate]) -> <f> Throttled function
fn <f> Function to debounce
ms <n|250> Interval in milliseconds
immediate <b|false> If true, function is called once immediately
@*/
Ox.debounce = function(fn/*, ms, immediate*/) {
var args,
immediate = Ox.last(arguments) === true,
ms = Ox.isNumber(arguments[1]) ? arguments[1] : 250,
timeout;
return function() {
args = arguments;
if (!timeout) {
if (immediate) {
fn.apply(null, args);
args = null;
}
} else {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
if (args !== null) {
fn.apply(null, args);
}
timeout = null;
}, ms);
};
};
/*@ /*@
Ox.time <f> Returns the time it takes to execute a given function Ox.time <f> Returns the time it takes to execute a given function
(fn) -> <n> Time in milliseconds (fn) -> <n> Time in milliseconds