Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created November 2, 2019 01:24
Show Gist options
  • Save luisenriquecorona/5bcfa0aed646e432e57875768cc87475 to your computer and use it in GitHub Desktop.
Save luisenriquecorona/5bcfa0aed646e432e57875768cc87475 to your computer and use it in GitHub Desktop.
As MXHR responses grow larger, it becomes necessary to process each resource as it is received, rather than waiting for the entire response. This can be done by listening for readyState 3:
var req = new XMLHttpRequest();
var getLatestPacketInterval, lastLength = 0;
req.open('GET', 'rollup_images.php', true);
req.onreadystatechange = readyStateHandler;
req.send(null);
function readyStateHandler{
if (req.readyState === 3 && getLatestPacketInterval === null) {
// Start polling.
getLatestPacketInterval = window.setInterval(function() {
getLatestPacket();
}, 15);
}
if (req.readyState === 4) {
// Stop polling.
clearInterval(getLatestPacketInterval);
// Get the last packet.
getLatestPacket();
}
}
function getLatestPacket() {
var length = req.responseText.length;
var packet = req.responseText.substring(lastLength, length);
processPacket(packet);
lastLength = length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment