JAVASCRIPT

Simple Client-Side API Request Queue with Delay (JavaScript)

Implement a basic JavaScript queue to process API requests with a delay, preventing rate limit issues for external services without complex retry logic.

class ApiRequestQueue {
    constructor(delayMs = 200) {
        this.queue = [];
        this.isRunning = false;
        this.delayMs = delayMs;
    }

    /**
     * Adds a request function to the queue.
     * The request function should be an async function that returns a Promise.
     * @param {function(): Promise<any>} requestFn - The async function to execute.
     * @returns {Promise<any>} A promise that resolves with the result of the request function.
     */
    addRequest(requestFn) {
        return new Promise((resolve, reject) => {
            this.queue.push({ requestFn, resolve, reject });
            if (!this.isRunning) {
                this.processQueue();
            }
        });
    }

    async processQueue() {
        this.isRunning = true;
        while (this.queue.length > 0) {
            const { requestFn, resolve, reject } = this.queue.shift();
            try {
                const result = await requestFn();
                resolve(result);
            } catch (error) {
                reject(error);
            }
            // Wait for the specified delay before processing the next item
            if (this.queue.length > 0) {
                await new Promise(res => setTimeout(res, this.delayMs));
            }
        }
        this.isRunning = false;
    }
}

// --- Example Usage ---
const myApiQueue = new ApiRequestQueue(500); // 500ms delay between requests
const TEST_API_URL = 'https://jsonplaceholder.typicode.com/todos/';

async function simulatedApiCall(id) {
    console.log(`[${new Date().toLocaleTimeString()}] Making API call for ID: ${id}`);
    try {
        const response = await fetch(TEST_API_URL + id);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        console.log(`[${new Date().toLocaleTimeString()}] Received data for ID ${id}: ${data.title.substring(0, 20)}...`);
        return data;
    } catch (error) {
        console.error(`[${new Date().toLocaleTimeString()}] Error fetching data for ID ${id}:`, error.message);
        throw error;
    }
}

// Add several requests to the queue
(async () => {
    console.log('Adding requests to queue...');
    for (let i = 1; i <= 5; i++) {
        myApiQueue.addRequest(() => simulatedApiCall(i))
            .then(data => {
                // console.log(`Finished request for ID ${data.id}`);
            })
            .catch(error => {
                // console.error(`Failed request for ID ${i}`);
            });
    }
    console.log('All requests added to queue. Processing will begin shortly...');

    // You can also await individual requests if needed
    try {
        const singleResult = await myApiQueue.addRequest(() => simulatedApiCall(6));
        console.log(`
[${new Date().toLocaleTimeString()}] Awaited single result for ID 6: ${singleResult.title.substring(0, 20)}...`);
    } catch (error) {
        console.error(`
[${new Date().toLocaleTimeString()}] Awaited single request for ID 6 failed.`);
    }
})();
How it works: This JavaScript snippet implements a simple client-side queue for API requests, designed to introduce a delay between calls. This is useful for managing interactions with external APIs that have strict rate limits, preventing your application from sending too many requests too quickly. Requests are added to the queue as functions, and the `processQueue` method asynchronously executes them one by one, pausing for a configurable `delayMs` between each successful or failed execution.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs