diff --git a/source/Ox/js/Function.js b/source/Ox/js/Function.js index a72ca3e0..bbcdf9aa 100644 --- a/source/Ox/js/Function.js +++ b/source/Ox/js/Function.js @@ -58,6 +58,37 @@ Ox.cache = function(fn, options) { return ret; }; +/*@ +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.identity Returns its first argument This can be used as a default iterator @@ -157,49 +188,18 @@ 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); + fn.apply(null, args); + args = null; + timeout = setTimeout(function() { + if (args !== null) { + fn.apply(null, args); + } + timeout = null; + }, ms); + }; }; };