From f9e90f9cd080417b868a15938a86ab66132be42b Mon Sep 17 00:00:00 2001 From: tophf Date: Sat, 22 Apr 2017 21:02:49 +0300 Subject: [PATCH] code cosmetics: simplify debounce() --- messaging.js | 25 +++++++++++++------------ update.js | 2 +- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/messaging.js b/messaging.js index 0a1ad059..81fe30ca 100644 --- a/messaging.js +++ b/messaging.js @@ -204,19 +204,20 @@ function tryJSONparse(jsonString) { } -function debounce(fn, delay, ...args) { - const timers = debounce.timers = debounce.timers || new Map(); - debounce.run = debounce.run || ((fn, ...args) => { - timers.delete(fn); +const debounce = Object.assign((fn, delay, ...args) => { + clearTimeout(debounce.timers.get(fn)); + debounce.timers.set(fn, setTimeout(debounce.run, delay, fn, ...args)); +}, { + timers: new Map(), + run(fn, ...args) { + debounce.timers.delete(fn); fn(...args); - }); - debounce.unregister = debounce.unregister || (fn => { - clearTimeout(timers.get(fn)); - timers.delete(fn); - }); - clearTimeout(timers.get(fn)); - timers.set(fn, setTimeout(debounce.run, delay, fn, ...args)); -} + }, + unregister(fn) { + clearTimeout(debounce.timers.get(fn)); + debounce.timers.delete(fn); + }, +}); function deepCopy(obj) { diff --git a/update.js b/update.js index 37a65a07..aeee808b 100644 --- a/update.js +++ b/update.js @@ -66,7 +66,7 @@ var updater = { if (interval) { const elapsed = Math.max(0, Date.now() - updater.lastUpdateTime); debounce(updater.checkAllStyles, Math.max(10e3, interval - elapsed)); - } else if (debounce.timers) { + } else { debounce.unregister(updater.checkAllStyles); } },