From 92a122eb0a95734f5e65abcb1efdcb27b2b13dfd Mon Sep 17 00:00:00 2001 From: j <0x006A@0x2620.org> Date: Sun, 2 Feb 2014 01:15:17 +0530 Subject: [PATCH] add Ox.throttle and Ox.debounce --- source/Ox/js/Function.js | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) 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