As others have said, you don't need a loop. You need something to keep track of how many times the button has been clicked.
However, this is tricky because you don't know whether the user will click the button before or after the response has returned. If they click the button before the response gets back, you need to loop when the response gets back to catch up to the number of button clicks that have already taken place. If they click the button after the response returns, you have to hold on to the response and use it upon the user's click.
A clean way to resolve this uncertainty is to use Promise
s. They will allow you to write the logic just once and not concern yourself with whether the response has arrived yet or not.
plnkr example
<button type="button" onclick="loadDoc()">Scimba text</button>
<script>
window.loadDoc = (function () {
var i = 1;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "info1.txt", true);
xhttp.send();
// create a promise for the result
var pResponse = new Promise(function (resolve) {
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
resolve(xhttp.responseText);
}
};
});
return function () {
if (i < 5) {
var c = i;
// chain off the promise once for each click
pResponse.then(function (response) {
document.getElementById(c).innerHTML = response;
});
i += 1;
}
};
})();
</script>