Skip to content

Commit 53f7716

Browse files
committed
Extract helper
1 parent 4153fb1 commit 53f7716

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

src/core/core.controller.js

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {each, callback as callCallback, uid, valueOrDefault, _elementsEqual} fro
1111
import {clearCanvas, clipArea, unclipArea, _isPointInArea} from '../helpers/helpers.canvas';
1212
// @ts-ignore
1313
import {version} from '../../package.json';
14+
import {debounce} from '../helpers/helpers.extras';
1415

1516
/**
1617
* @typedef { import("../platform/platform.base").ChartEvent } ChartEvent
@@ -122,7 +123,7 @@ class Chart {
122123
this.attached = false;
123124
this._animationsDisabled = undefined;
124125
this.$context = undefined;
125-
this._resizeTimer = undefined;
126+
this._doResize = debounce(() => this.update('resize'), options.resizeDelay || 0);
126127

127128
// Add the chart instance to the global namespace
128129
instances[me.id] = me;
@@ -243,14 +244,9 @@ class Chart {
243244
callCallback(options.onResize, [newSize], me);
244245

245246
if (me.attached) {
246-
const delay = options.resizeDelay || 0;
247-
const resizeUpdate = () => me.update('resize');
248-
if (delay) {
249-
clearTimeout(me._resizeTimer);
250-
me._resizeTimer = setTimeout(resizeUpdate, delay);
247+
if (me._doResize()) {
248+
// The resize update is delayed, only draw without updating.
251249
me.render();
252-
} else {
253-
resizeUpdate();
254250
}
255251
}
256252
}

src/helpers/helpers.extras.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,25 @@ export function throttled(fn, thisArg, updateFn) {
4040
};
4141
}
4242

43+
/**
44+
* Debounces calling `fn` for `delay` ms
45+
* @param {function} fn - Function to call. No arguments are passed.
46+
* @param {number} delay - Delay in ms. 0 = immediate invocation.
47+
* @returns {function}
48+
*/
49+
export function debounce(fn, delay) {
50+
let timeout;
51+
return function() {
52+
if (delay) {
53+
clearTimeout(timeout);
54+
timeout = setTimeout(fn, delay);
55+
} else {
56+
fn();
57+
}
58+
return delay;
59+
};
60+
}
61+
4362

4463
/**
4564
* Converts 'start' to 'left', 'end' to 'right' and others to 'center'

0 commit comments

Comments
 (0)