mirror of
https://github.com/nasa/openmct.git
synced 2025-06-05 00:50:49 +00:00
* created a throttle util and using it in timer plugin to throttle refreshing the timer domain object * Simplify timer logic * Clarify code a little * refactor: lint:fix * Fix linting issue --------- Co-authored-by: Jamie V <jamie.j.vigliotta@nasa.gov> Co-authored-by: Jesse Mazzella <jesse.d.mazzella@nasa.gov> Co-authored-by: Jesse Mazzella <ozyx@users.noreply.github.com>
35 lines
1015 B
JavaScript
35 lines
1015 B
JavaScript
/**
|
|
* Creates a throttled function that only invokes the provided function at most once every
|
|
* specified number of milliseconds. Subsequent calls within the waiting period will be ignored.
|
|
* @param {Function} func The function to throttle.
|
|
* @param {number} wait The number of milliseconds to wait between successive calls to the function.
|
|
* @return {Function} Returns the new throttled function.
|
|
*/
|
|
export default function throttle(func, wait) {
|
|
let timeout;
|
|
let result;
|
|
let previous = 0;
|
|
|
|
return function (...args) {
|
|
const now = new Date().getTime();
|
|
const remaining = wait - (now - previous);
|
|
|
|
if (remaining <= 0 || remaining > wait) {
|
|
if (timeout) {
|
|
clearTimeout(timeout);
|
|
timeout = null;
|
|
}
|
|
|
|
previous = now;
|
|
result = func(...args);
|
|
} else if (!timeout) {
|
|
timeout = setTimeout(() => {
|
|
previous = new Date().getTime();
|
|
timeout = null;
|
|
result = func(...args);
|
|
}, remaining);
|
|
}
|
|
return result;
|
|
};
|
|
}
|