bigbluebutton-Github/bigbluebutton-html5/imports/utils/throttle.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

export function throttle(func, delay, options = {}) {
let timeoutId;
let lastExecTime = 0;
let leadingExec = true;
const { leading = true, trailing = true } = options;
2023-08-25 01:49:05 +08:00
let cancelPendingExecution = false; // Flag to track cancellation
const throttledFunction = function () {
const context = this;
const args = arguments;
const elapsed = Date.now() - lastExecTime;
function execute() {
2023-08-25 01:49:05 +08:00
if (!cancelPendingExecution) { // Only execute if not cancelled
func.apply(context, args);
lastExecTime = Date.now();
}
}
if (leadingExec && leading) {
execute();
leadingExec = false;
const nextExecDelay = elapsed < delay ? delay - elapsed : 0;
setTimeout(function () {
leadingExec = true;
}, nextExecDelay);
} else if (!timeoutId && trailing) {
timeoutId = setTimeout(function () {
execute();
timeoutId = null;
}, delay - elapsed);
}
2023-08-25 01:49:05 +08:00
};
// Add a cancel method to the throttled function
throttledFunction.cancel = function () {
cancelPendingExecution = true;
clearTimeout(timeoutId);
timeoutId = null;
};
return throttledFunction;
}