From 136506da40229d4a4e52a36e3bb9361d6cc5d7da Mon Sep 17 00:00:00 2001 From: juliandescottes Date: Sun, 20 Nov 2016 12:08:31 +0100 Subject: [PATCH] issue #374 throttle calls to currentColorsService update function --- src/js/service/CurrentColorsService.js | 7 ++++++- src/js/utils/FunctionUtils.js | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/js/service/CurrentColorsService.js b/src/js/service/CurrentColorsService.js index b58d251c..365bfb0b 100644 --- a/src/js/service/CurrentColorsService.js +++ b/src/js/service/CurrentColorsService.js @@ -10,11 +10,16 @@ this.cachedFrameProcessor = new pskl.model.frame.AsyncCachedFrameProcessor(); this.cachedFrameProcessor.setFrameProcessor(this.getFrameColors_.bind(this)); + this.throttledUpdateCurrentColors_ = pskl.utils.FunctionUtils.throttle( + this.updateCurrentColors_.bind(this), + 1000 + ); + this.paletteService = pskl.app.paletteService; }; ns.CurrentColorsService.prototype.init = function () { - $.subscribe(Events.HISTORY_STATE_SAVED, this.updateCurrentColors_.bind(this)); + $.subscribe(Events.HISTORY_STATE_SAVED, this.throttledUpdateCurrentColors_); $.subscribe(Events.HISTORY_STATE_LOADED, this.loadColorsFromCache_.bind(this)); }; diff --git a/src/js/utils/FunctionUtils.js b/src/js/utils/FunctionUtils.js index 71a05b1c..9c8233e1 100644 --- a/src/js/utils/FunctionUtils.js +++ b/src/js/utils/FunctionUtils.js @@ -2,6 +2,9 @@ var ns = $.namespace('pskl.utils'); ns.FunctionUtils = { + /** + * Returns a memoized version of the provided function. + */ memo : function (fn, cache, scope) { var memoized = function () { var key = Array.prototype.join.call(arguments, '-'); @@ -11,6 +14,27 @@ return cache[key]; }; return memoized; + }, + + /** + * Returns a throttled version of the provided method, that will be called at most + * every X milliseconds, where X is the provided interval. + */ + throttle : function (fn, interval) { + var last, timer; + return function () { + var now = Date.now(); + if (last && now < last + interval) { + clearTimeout(timer); + timer = setTimeout(function () { + last = now; + fn(); + }, interval); + } else { + last = now; + fn(); + } + }; } }; })();