You do not need a setTimout
(so you don't need to cancel the setTimeout), and you do not need to cancel the fetch.
To use a value inside a React component, you have to use a React state. React would not know about changes to some outside object (like your singleton object).
You can store the timestamps of the last n requests, and if the first one is older than the time period, you can remove it and make a new request.
const useLimitedRequests = function(){
const limit = 5;
const timePeriod = 6 * 1000;
const [ requests, setRequests ] = useState([]);
return [
requests,
function(){
const now = Date.now();
if( requests.length > 0 && (requests[0] < now - timePeriod) ){
setRequests( requests.slice(1) );
}
if( requests.length < limit ){
setRequests([ ...requests, now ]);
return now;
}
return 0;
}
];
};
export const LimitedRequests = (props)=>{
const [ requests, addRequest ] = useLimitedRequests();
return (<>
<button onClick={ ()=>{
if( addRequest() > 0 ){
console.log('ok, do fetch again');
} else {
console.log('no no, you have to wait');
}
}}>
fetch again
</button>
{ requests.map(function( req ){
return <div key={ req }>{ req }</div>;
})}
</>);
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…