javascript / expert
Snippet
Async Generator Pipeline Control for Shielding React UI from Rate-Limit Flooding
Async Generators yield items asynchronously over time, enabling custom control flow algorithms for client-side rate limiting and request throttling in React. Consuming an `AsyncGenerator` with `for await...of` inside a cleanup-aware React `useEffect` hook ensures backpressure handling and prevents API flooding.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { useEffect } from 'react';async function* rateLimitedQueue(requests: string[], delayMs: number): AsyncGenerator<string, void, unknown> {for (const req of requests) {yield req;await new Promise(resolve => setTimeout(resolve, delayMs));}}export function useBatchProcessor(items: string[], onProcess: (item: string) => void) {useEffect(() => {let active = true;(async () => {for await (const item of rateLimitedQueue(items, 300)) {if (!active) break;onProcess(item);}})();return () => { active = false; };}, [items, onProcess]);}
react
Breakdown
1
async function* rateLimitedQueue(requests: string[], delayMs: number): AsyncGenerator<string, void, unknown>
Creates an asynchronous generator function that yields items sequentially with enforced delay intervals.
2
for await (const item of rateLimitedQueue(items, 300)) {
Consumes the async generator iterable inside React's execution lifecycle while controlling request timing.
3
return () => { active = false; };
Implements an explicit cancellation flag to prevent state updates if the React component unmounts mid-stream.