diff --git a/source/Ox/js/Function.js b/source/Ox/js/Function.js index 5465121b..a72ca3e0 100644 --- a/source/Ox/js/Function.js +++ b/source/Ox/js/Function.js @@ -147,6 +147,62 @@ Ox.queue = function(fn, maxThreads) { return ret; }; +/*@ +Ox.throttle Runs a function at most once per given time frame + (fn[, ms]) -> Throttled function + fn Function to throttle + ms 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 Runs a function once it stops being called for a given time frame + (fn[, ms][, immediate]) -> Throttled function + fn Function to debounce + ms Interval in milliseconds + immediate 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 Returns the time it takes to execute a given function (fn) -> Time in milliseconds