Created
June 18, 2023 23:32
-
-
Save sinau123/8709ae9c7e7e48340e6dbd3ad78713d8 to your computer and use it in GitHub Desktop.
debounce & throttle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let debounce = (func, delay) => { | |
let timeoutId = ref(None); | |
data => { | |
switch (timeoutId^) { | |
| Some(existingTimeout) => Js.Global.clearTimeout(existingTimeout) | |
| None => () | |
}; | |
timeoutId := Some(Js.Global.setTimeout(() => {func(data)}, delay)); | |
}; | |
}; | |
let throttle = (func, delay) => { | |
let canRun = ref(true); | |
data => | |
if (canRun^) { | |
func(data); | |
canRun := false; | |
let _ = Js.Global.setTimeout(() => {canRun := true}, delay); | |
(); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment