UNPKG

rescript-debounce

Version:
101 lines (95 loc) 2.52 kB
// Generated by ReScript, PLEASE EDIT WITH CARE import * as Caml_option from "rescript/lib/es6/caml_option.js"; function makeControlled(waitOpt, fn) { var wait = waitOpt !== undefined ? waitOpt : 100; var timerId = { contents: undefined }; var lastArg = { contents: undefined }; var lastCallTime = { contents: undefined }; var shouldCall = function (time) { var lastCallTime$1 = lastCallTime.contents; if (lastCallTime$1 === undefined) { return true; } var timeSinceLastCall = time - lastCallTime$1 | 0; if (timeSinceLastCall >= wait) { return true; } else { return timeSinceLastCall < 0; } }; var remainingWait = function (time) { var lastCallTime$1 = lastCallTime.contents; if (lastCallTime$1 === undefined) { return wait; } var timeSinceLastCall = time - lastCallTime$1 | 0; return wait - timeSinceLastCall | 0; }; var timerExpired = function () { var timerId$1 = timerId.contents; if (timerId$1 !== undefined) { clearTimeout(Caml_option.valFromOption(timerId$1)); } var time = Date.now() | 0; if (shouldCall(time)) { return call(); } else { timerId.contents = Caml_option.some(setTimeout(timerExpired, remainingWait(time))); return ; } }; var call = function () { var x = lastArg.contents; if (x !== undefined) { lastArg.contents = undefined; timerId.contents = undefined; return fn(Caml_option.valFromOption(x)); } else { timerId.contents = undefined; return ; } }; var schedule = function (x) { var time = Date.now() | 0; lastArg.contents = Caml_option.some(x); lastCallTime.contents = time; timerId.contents = Caml_option.some(setTimeout(timerExpired, wait)); }; var scheduled = function () { return timerId.contents !== undefined; }; var cancel = function () { var timerId$p = timerId.contents; if (timerId$p !== undefined) { clearTimeout(Caml_option.valFromOption(timerId$p)); timerId.contents = undefined; lastArg.contents = undefined; lastCallTime.contents = undefined; return ; } }; var invoke = function (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 */