@puls-atlas/cli
Version:
The Puls Atlas CLI tool for managing Atlas projects
69 lines • 1.52 kB
JavaScript
export default (callback, delay = 166, options = {}) => {
const {
isTrailing = true,
isLeading = true,
debounceMode = false
} = options;
let timeoutID;
let isCancelled = false;
let lastExec = 0;
let funcArgs = null;
let context = null;
const clearExistingTimeout = () => {
if (timeoutID) {
clearTimeout(timeoutID);
}
};
const cancel = options => {
const {
upcomingOnly = false
} = options ?? {};
clearExistingTimeout();
isCancelled = !upcomingOnly;
};
const clear = () => {
cancel({
upcomingOnly: true
});
};
const flush = () => {
if (isCancelled) {
return;
}
clear();
callback.apply(context, funcArgs);
};
const exec = () => {
lastExec = Date.now();
callback.apply(context, funcArgs);
};
const wrapper = (...args) => {
if (delay === 0) {
callback.apply(this, args);
}
if (isCancelled) {
return;
}
const elapsed = Date.now() - lastExec;
context = this;
funcArgs = args;
clearExistingTimeout();
if (!debounceMode && elapsed > delay) {
if (!isLeading) {
lastExec = Date.now();
if (isTrailing) {
timeoutID = setTimeout(exec, delay);
}
} else {
exec();
}
} else if (isTrailing) {
timeoutID = setTimeout(exec, debounceMode ? delay : delay - elapsed);
}
};
wrapper.cancel = cancel;
wrapper.clear = clear;
wrapper.flush = flush;
wrapper.exec = exec;
return wrapper;
};