From 8e9d92cc98869ca372a993851722a73451d10f58 Mon Sep 17 00:00:00 2001 From: Gary Katsevman Date: Mon, 13 Aug 2018 16:39:50 -0400 Subject: [PATCH] fix: add debounced.cancel and use it in ResizeManager (#5378) It's possible that ResizeManager will trigger its debounce handler but then get disposed before the handler runs. This can cause tests to fail, so, instead, we should cancel the debounce when ResizeManager is disposed. --- src/js/resize-manager.js | 4 ++++ src/js/utils/fn.js | 11 ++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/js/resize-manager.js b/src/js/resize-manager.js index 7303fc0d0..6e2302ad2 100644 --- a/src/js/resize-manager.js +++ b/src/js/resize-manager.js @@ -114,6 +114,10 @@ class ResizeManager extends Component { this.off('load', this.loadListener_); } + if (this.debouncedHandler_) { + this.debouncedHandler_.cancel(); + } + this.ResizeObserver = null; this.resizeObserver = null; this.debouncedHandler_ = null; diff --git a/src/js/utils/fn.js b/src/js/utils/fn.js index 63e10087d..959154190 100644 --- a/src/js/utils/fn.js +++ b/src/js/utils/fn.js @@ -98,8 +98,13 @@ export const throttle = function(fn, wait) { export const debounce = function(func, wait, immediate, context = window) { let timeout; + const cancel = () => { + context.clearTimeout(timeout); + timeout = null; + }; + /* eslint-disable consistent-this */ - return function() { + const debounced = function() { const self = this; const args = arguments; @@ -119,4 +124,8 @@ export const debounce = function(func, wait, immediate, context = window) { timeout = context.setTimeout(later, wait); }; /* eslint-enable consistent-this */ + + debounced.cancel = cancel; + + return debounced; };