Skip to content

Instantly share code, notes, and snippets.

@jcb121
Created December 15, 2022 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcb121/8ac8243638b3f4523cbbb24d32d6a6fc to your computer and use it in GitHub Desktop.
Save jcb121/8ac8243638b3f4523cbbb24d32d6a6fc to your computer and use it in GitHub Desktop.
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