Created
December 15, 2022 23:58
-
-
Save jcb121/8ac8243638b3f4523cbbb24d32d6a6fc to your computer and use it in GitHub Desktop.
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
import React, { | |
useCallback, | |
useRef | |
} from "https://cdn.skypack.dev/react@17.0.1"; | |
import { render } from "https://cdn.skypack.dev/react-dom@17.0.1"; | |
let apiFetching = false; | |
let apiLastRun = Date.now(); | |
const SYNC_TASK_DELAY = 500; | |
function ApiFunction() { | |
if (apiFetching) | |
throw new Error( | |
"API CALLED TOO MANY TIMES last called:" + | |
(Date.now() - apiLastRun) + | |
"GIVEN DELAY" + | |
delay | |
); | |
apiFetching = true; | |
apiLastRun = Date.now(); | |
setTimeout(function () { | |
apiFetching = false; | |
}, SYNC_TASK_DELAY); | |
} | |
const container = document.getElementById("root"); | |
const Component = () => { | |
const lastCall = useRef(); | |
const requests = useRef(0); | |
const handleClick = useCallback(() => { | |
const now = Date.now(); | |
const timeSinceLastCall = now - lastCall.current; | |
requests.current++; | |
lastCall.current = now; | |
const waitTime = requests.current * SYNC_TASK_DELAY; | |
let delayTime = | |
timeSinceLastCall > waitTime ? 0 : waitTime - timeSinceLastCall; | |
// if the delay time is 0, we have completed all requests. | |
if (delayTime === 0) | |
requests.current = 0; | |
setTimeout(() => { | |
ApiFunction(); | |
}, delayTime); | |
}, []); | |
return <button onClick={handleClick}>HelloWorld</button>; | |
}; | |
render(<Component />, container); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment