How to simulate typing in my textarea with Chat GPT's API in JavaScript using real-time server-sent events

35 Views Asked by At

I have this code. It works perfectly in my local environment, but on live server, the whole text is shown all at once, it does not simulate typing.

Create a new EventSource object for real-time server-sent events (SSE)

    // Create a new EventSource object for real-time server-sent events (SSE)
    const source = new EventSource(url);

    // Initialize the response content and current index for displaying typed characters
    let responseContent = '';
    const streamingTextElement = document.getElementById('generated_text');
    let currentIndex = 0;

A function that types out received chunks character by character I tried streamingTextElement.textContent as well

    function typeCharacter() {
        if (currentIndex < responseContent.length - 9) {
            streamingTextElement.value += responseContent.charAt(currentIndex);
            currentIndex++;
            setTimeout(typeCharacter, 100); // Adjust the typing speed by changing the delay (in milliseconds)
        }
    }

Process the received SSE events

    // Process the received SSE events
    source.onmessage = function (event) {
        if (event.data == '[DONE]') {
            // All data received, logging it and closing the connection
            const submitButton = document.querySelector('.fmai-submit-btn');
            submitButton.disabled = false;
            document.querySelector('.loading-tea').style.display = 'none';
            
            console.log('All data received:', responseContent);
            source.close(); // Close the connection

            return;
        }

        const data = JSON.parse(event.data);

        if (data.id) {
            // Process the data message chunk
            const choices = data.choices;

            if (choices && choices.length > 0) {
                const content = choices[0].delta.content;

                responseContent += content;
                typeCharacter();

                // Auto-scroll to the bottom as new content is added
                streamingTextElement.scrollTop = streamingTextElement.scrollHeight;
            }
        } 
    };

Handling errors in receiving SSE events

    // Handling errors in receiving SSE events
    source.onerror = function (error) {
        const submitButton = document.querySelector('.fmai-submit-btn');
        submitButton.disabled = false;
        document.querySelector('.loading-tea').style.display = 'none';
        
        fmaiNotification.style.display = 'block';
        fmaiNotificationMsg.innerHTML = `We couldn't connect, try again.`;

        setTimeout(() => {
            fmaiNotification.style.display = 'none';
            fmaiNotificationMsg.innerHTML = '';
        }, 1500);

    
        // console.error('Error:', error);
        source.close(); // Close the connection
    };

enter image description here

0

There are 0 best solutions below