From f34855573ef203182994eac6d9ecaa027225dd48 Mon Sep 17 00:00:00 2001 From: Bruno Windels Date: Thu, 7 Feb 2019 16:24:26 +0000 Subject: [PATCH] replace ratelimitedfunc with lodash impl --- src/ratelimitedfunc.js | 58 ++++++++++++------------------------------ 1 file changed, 16 insertions(+), 42 deletions(-) diff --git a/src/ratelimitedfunc.js b/src/ratelimitedfunc.js index 20f6db79b8..1f15f11d91 100644 --- a/src/ratelimitedfunc.js +++ b/src/ratelimitedfunc.js @@ -20,54 +20,28 @@ limitations under the License. * to update the interface once for all of them. * * Note that the function must not take arguments, since the args - * could be different for each invocarion of the function. + * could be different for each invocation of the function. * * The returned function has a 'cancelPendingCall' property which can be called * on unmount or similar to cancel any pending update. */ -module.exports = function(f, minIntervalMs) { - this.lastCall = 0; - this.scheduledCall = undefined; - const self = this; - const wrapper = function() { - const now = Date.now(); +import { throttle } from "lodash"; - if (self.lastCall < now - minIntervalMs) { - f.apply(this); - // get the time again now the function has finished, so if it - // took longer than the delay time to execute, it doesn't - // immediately become eligible to run again. - self.lastCall = Date.now(); - } else if (self.scheduledCall === undefined) { - self.scheduledCall = setTimeout( - () => { - self.scheduledCall = undefined; - f.apply(this); - // get time again as per above - self.lastCall = Date.now(); - }, - (self.lastCall + minIntervalMs) - now, - ); - } +export default function ratelimitedfunc(fn, time) { + const throttledFn = throttle(fn, time, { + leading: true, + trailing: true, + }); + const _bind = throttledFn.bind; + throttledFn.bind = function() { + const boundFn = _bind.apply(throttledFn, arguments); + boundFn.cancelPendingCall = throttledFn.cancelPendingCall; + return boundFn; }; - // add the cancelPendingCall property - wrapper.cancelPendingCall = function() { - if (self.scheduledCall) { - clearTimeout(self.scheduledCall); - self.scheduledCall = undefined; - } + throttledFn.cancelPendingCall = function() { + throttledFn.cancel(); }; - - // make sure that cancelPendingCall is copied when react rebinds the - // wrapper - const _bind = wrapper.bind; - wrapper.bind = function() { - const rebound = _bind.apply(this, arguments); - rebound.cancelPendingCall = wrapper.cancelPendingCall; - return rebound; - }; - - return wrapper; -}; + return throttledFn; +}