@carbon/react
Version:
React components for the Carbon Design System
58 lines (52 loc) • 1.29 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import window from 'window-or-global';
// mdn resize function
/**
* A callback function to be executed on `resize`.
*/
const OptimizedResize = (() => {
const callbacks = [];
let running = false;
const runCallbacks = () => {
callbacks.forEach(callback => {
callback();
});
running = false;
};
const handleResize = () => {
if (!running) {
running = true;
window.requestAnimationFrame(runCallbacks);
}
};
const addCallback = callback => {
const index = callbacks.indexOf(callback);
if (index < 0) {
callbacks.push(callback);
}
};
return {
/** Adds a callback function to be executed on window `resize`. */
add: callback => {
if (!callbacks.length) {
window.addEventListener('resize', handleResize);
}
addCallback(callback);
return {
/** Removes the callback. */
remove: () => {
const index = callbacks.indexOf(callback);
if (index >= 0) {
callbacks.splice(index, 1);
}
}
};
}
};
})();
export { OptimizedResize };