Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 337527
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T10:20:39+00:00 2026-05-12T10:20:39+00:00

How in JavaScript process unhandled yet part of XMLHttpRequest responseText only in onprogress/onreadystatechange handler,

  • 0

How in JavaScript process unhandled yet part of XMLHttpRequest responseText only in onprogress/onreadystatechange handler, without using global variables for XMLHttpRequest, prevDataLength, nextreadPos and inProgress (for locking)?

The problem is the following: I want to update web page based on currently received part of data obtained using AJAX (current value of responseText of XMLHttprequest). I want to update page as soon as server sends data (it is so called HTTP streaming pattern). When I do update, I want to process only yet unhandled part of responseText.

Additional complication is that responseText may contain unfinished fragment of response; one can easily deal with that (like I do) by using terminators; then you can easily extract complete responses.

Currently I use global variables and locking to avoid problem where handler is called while earlier call didn’t finished working (processing new data). My code looks (simplified) like the following:

function processData(unprocessed, nextReadPos) {
    var lastLineEnd = unprocessed.lastIndexOf('\n');
    if (lastLineEnd !== -1) {
        var lines = unprocessed.substring(0, lastLineEnd).split('\n');
        nextReadPos += lastLineEnd + 1 /* 1 == '\n'.length */;

        processLines(lines);
    } // end if

    return nextReadPos;
}

function handleResponse() {
    ...
    // here xhr.readyState === 4 && xhr.status === 200
    // in case we were called before finished processing
    if (inProgress) {
        return;
    } else {
        inProgress = true;
    }

    // extract new whole (complete) lines, and process them
    while (prevDataLength !== xhr.responseText.length) {
        if (xhr.readyState === 4 &&
            prevDataLength === xhr.responseText.length) {
            break;
        }

        prevDataLength = xhr.responseText.length;
        var unprocessed = xhr.responseText.substring(nextReadPos);
        nextReadPos = processData(unprocessed, nextReadPos);
    } // end while
    ...
    inProgress = false;
}
...
xhr.onreadystatechange = handleResponse;

If I have simpler handler I could protect against re-entering handler when it didn’t finish work by passing XMLHttpRequest object as parameter, like e.g. case 1 in “Step 3 – A Simple Example” section of AJAX/Getting_Started article at Mozilla Developer Centre:

httpRequest.onreadystatechange = function() { alertContents(httpRequest); };  //1 (simultaneous request)

which in notation used in larger fragment of code is

xhr.onreadystatechange = function() { handleResponse(xhr); };  //1 (simultaneous request)

But that example doesn’t tell me what to do with other global variables: prevDataLength and nextReadPos. They are used to decide if there is any new data, and to extract complete ‘sentences’ from server response, respectively.

How to do that without global variables?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T10:20:39+00:00Added an answer on May 12, 2026 at 10:20 am

    I am answering my own question, because there were no other answers

    First, the global variable inProgress, used as semaphor / mutex to protect critical section, and while (prevDataLength !== xhr.responseText.length) { ... } loop is not needed at all.

    According to William’s answer to Are mutexes needed in JavaScript? StackOverflow question:

    Javascript is defined as a reentrant language which means there is no threading exposed to the user, there may be threads in the implementation. Functions like setTimeout() and asynchronous callbacks need to wait for the script engine to sleep before they’re able to run.

    This agrees with description in “Document Object Model (DOM) Level 3 Events W3C Specification”, chapter 1. “Document Object Model Events”, section 1.2 “Event dispatch and DOM event flow”, last paragraph:

    The DOM event model is reentrant. Event listeners may perform actions that cause additional events to be dispatched. Such events are handled in a synchronous manner, the event propagation that causes the event listener to be triggered will resume only after the event dispatch of the new event is completed.

    That means that everything that happens in an event must be finished before the next event will be processed.


    Second, global variables prevDataLength and nextReadPos could (and probably should) be added as additional extra properties to XmlHttpRequest object.

    Alternate solution would be to use closures to have private / static variables, as described somewhat in Private Members in JavaScript by Douglas Crockford, and in Example 3: Encapsulating Related Functionality in comp.lang.javascript FAQ notes :: Javascript Closures.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 176k
  • Answers 176k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This instance of SQL Server is running on the same… May 12, 2026 at 3:15 pm
  • Editorial Team
    Editorial Team added an answer A dependent name is essentially a name that depends on… May 12, 2026 at 3:15 pm
  • Editorial Team
    Editorial Team added an answer This should do: $('input:not(#x,#y)', theform).remove() May 12, 2026 at 3:15 pm

Related Questions

I want to execute a process named notepad.exe or any exes in javascript and
Nikhil Kothari's Script# is quite possibly one of the most amazing concepts I've seen
I have a set of global counter variables in Javascript: var counter_0 = 0;
Does anyone know if there are plans to implement JavaScript in MS Visual Studio,

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.