Skip to content

Commit

Permalink
Extract helper
Browse files Browse the repository at this point in the history
  • Loading branch information
kurkle committed Feb 23, 2021
1 parent 4153fb1 commit 53f7716
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
12 changes: 4 additions & 8 deletions src/core/core.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {each, callback as callCallback, uid, valueOrDefault, _elementsEqual} fro
import {clearCanvas, clipArea, unclipArea, _isPointInArea} from '../helpers/helpers.canvas';
// @ts-ignore
import {version} from '../../package.json';
import {debounce} from '../helpers/helpers.extras';

/**
* @typedef { import("../platform/platform.base").ChartEvent } ChartEvent
Expand Down Expand Up @@ -122,7 +123,7 @@ class Chart {
this.attached = false;
this._animationsDisabled = undefined;
this.$context = undefined;
this._resizeTimer = undefined;
this._doResize = debounce(() => this.update('resize'), options.resizeDelay || 0);

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

if (me.attached) {
const delay = options.resizeDelay || 0;
const resizeUpdate = () => me.update('resize');
if (delay) {
clearTimeout(me._resizeTimer);
me._resizeTimer = setTimeout(resizeUpdate, delay);
if (me._doResize()) {
// The resize update is delayed, only draw without updating.
me.render();
} else {
resizeUpdate();
}
}
}
Expand Down
19 changes: 19 additions & 0 deletions src/helpers/helpers.extras.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,25 @@ export function throttled(fn, thisArg, updateFn) {
};
}

/**
* Debounces calling `fn` for `delay` ms
* @param {function} fn - Function to call. No arguments are passed.
* @param {number} delay - Delay in ms. 0 = immediate invocation.
* @returns {function}
*/
export function debounce(fn, delay) {
let timeout;
return function() {
if (delay) {
clearTimeout(timeout);
timeout = setTimeout(fn, delay);
} else {
fn();
}
return delay;
};
}


/**
* Converts 'start' to 'left', 'end' to 'right' and others to 'center'
Expand Down

0 comments on commit 53f7716

Please sign in to comment.