rescript-debounce
Version:
Debounce for ReScript
98 lines (93 loc) • 2.45 kB
JavaScript
// Generated by ReScript, PLEASE EDIT WITH CARE
import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.js";
function makeControlled(waitOpt, fn) {
let wait = waitOpt !== undefined ? waitOpt : 100;
let timerId = {
contents: undefined
};
let lastArg = {
contents: undefined
};
let lastCallTime = {
contents: undefined
};
let shouldCall = time => {
let lastCallTime$1 = lastCallTime.contents;
if (lastCallTime$1 === undefined) {
return true;
}
let timeSinceLastCall = time - lastCallTime$1 | 0;
if (timeSinceLastCall >= wait) {
return true;
} else {
return timeSinceLastCall < 0;
}
};
let remainingWait = time => {
let lastCallTime$1 = lastCallTime.contents;
if (lastCallTime$1 === undefined) {
return wait;
}
let timeSinceLastCall = time - lastCallTime$1 | 0;
return wait - timeSinceLastCall | 0;
};
let timerExpired = () => {
let timerId$1 = timerId.contents;
if (timerId$1 !== undefined) {
clearTimeout(Primitive_option.valFromOption(timerId$1));
}
let time = Date.now() | 0;
if (shouldCall(time)) {
return call();
} else {
timerId.contents = Primitive_option.some(setTimeout(timerExpired, remainingWait(time)));
return;
}
};
let call = () => {
let x = lastArg.contents;
if (x !== undefined) {
lastArg.contents = undefined;
timerId.contents = undefined;
return fn(Primitive_option.valFromOption(x));
} else {
timerId.contents = undefined;
return;
}
};
let schedule = x => {
let time = Date.now() | 0;
lastArg.contents = Primitive_option.some(x);
lastCallTime.contents = time;
timerId.contents = Primitive_option.some(setTimeout(timerExpired, wait));
};
let scheduled = () => timerId.contents !== undefined;
let cancel = () => {
let timerId$p = timerId.contents;
if (timerId$p !== undefined) {
clearTimeout(Primitive_option.valFromOption(timerId$p));
timerId.contents = undefined;
lastArg.contents = undefined;
lastCallTime.contents = undefined;
return;
}
};
let invoke = x => {
cancel();
fn(x);
};
return {
invoke: invoke,
schedule: schedule,
scheduled: scheduled,
cancel: cancel
};
}
function make(wait, fn) {
return makeControlled(wait, fn).schedule;
}
export {
make,
makeControlled,
}
/* No side effect */