1

I need to make some delays in my loop, every time after some amount of data (after a few cycles/iterations through my loop) is sent to the server.

Sending data and receiving respond from the server works fine, but requested delays in loop still don't work.

Thanks a lot for your help.

EDIT: Code was changed, please check the third answer (mine).

<!DOCTYPE html>
<html>
<body>

<h2>AJAX</h2>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
    var xhttp = [];



    var code = [
"WOICEL0Q9P",
"ZJTS4GYJEJ",
"HJPMQOCX31",
"MP26N0BH01",
"7TJNYZIRJR",
"Z5MIDDG4N2",
"BX6MKYK0O7",
"KVFVH1ESQX",
"40ADY3ZBE5",
"V4NT360JR5",
"FDI8AFL680",
"ZH89N59XQR",
"M6OS2OX38H",
"D8O76YDLM0",
"86GBMJLIXY",
"1QRFVU26VK",
"HFUI9QV6DY",
"VN83OGR825",
"DDMPCBX2MF",
"2M3QFPI234"
    ];

    var i = code.length;
    var j = code.length;
    var k = 5000;

    var p = 0;


    while (i--) {
        var process = (function(i) {
            if (p == 5) {
                p = 0;
                function func(i) {
                    xhttp[i] = new XMLHttpRequest();
                    xhttp[i].onreadystatechange = function() {
                        if (xhttp[i].readyState == 4 && xhttp[i].status == 200) {
                            if (i == j) {
                                document.getElementById("demo").innerHTML = code[i] + ":   " + xhttp[i].responseText;
                            }
                            else {
                                document.getElementById("demo").innerHTML += "<br><br>" + code[i] + ":   " + xhttp[i].responseText;
                            }
                        }
                    };
                    xhttp[i].open("POST", "https://www.example.com/services/postdata.svc", true);
                    xhttp[i].setRequestHeader("Host", "www.example.com");
                    xhttp[i].setRequestHeader("Accept", "application/json, text/javascript");
                    xhttp[i].setRequestHeader("Accept-Language", "cs,en-US;q=0.7,en;q=0.3");
                    xhttp[i].setRequestHeader("Accept-Encoding", "gzip, deflate, br");
                    xhttp[i].setRequestHeader("Content-Type", "application/json; charset=utf-8");
                    xhttp[i].setRequestHeader("Cache-Control", "no-cache");
                    xhttp[i].setRequestHeader("X-Requested-With", "XMLHttpRequest");
                    xhttp[i].setRequestHeader("Referer", "https://www.example.com/postdata-test.htm");
                    xhttp[i].setRequestHeader("Content-Length", "37");
                    xhttp[i].setRequestHeader("Connection", "keep-alive");
                    xhttp[i].send('{"code":"'+code[i]+'","confirm":false}');
                    //console.log('hello - Test if delay is here');
                    p++;
                }
                setTimeout(func(i), k);
                k += 5000;
            }
            else {
                xhttp[i] = new XMLHttpRequest();
                xhttp[i].onreadystatechange = function() {
                    if (xhttp[i].readyState == 4 && xhttp[i].status == 200) {
                        if (i == j) {
                            document.getElementById("demo").innerHTML = code[i] + ":   " + xhttp[i].responseText;
                        }
                        else {
                            document.getElementById("demo").innerHTML += "<br><br>" + code[i] + ":   " + xhttp[i].responseText;
                        }
                    }
                };
                xhttp[i].open("POST", "https://www.example.com/services/postdata.svc", true);
                xhttp[i].setRequestHeader("Host", "www.example.com");
                xhttp[i].setRequestHeader("Accept", "application/json, text/javascript");
                xhttp[i].setRequestHeader("Accept-Language", "cs,en-US;q=0.7,en;q=0.3");
                xhttp[i].setRequestHeader("Accept-Encoding", "gzip, deflate, br");
                xhttp[i].setRequestHeader("Content-Type", "application/json; charset=utf-8");
                xhttp[i].setRequestHeader("Cache-Control", "no-cache");
                xhttp[i].setRequestHeader("X-Requested-With", "XMLHttpRequest");
                xhttp[i].setRequestHeader("Referer", "https://www.example.com/postdata-test.htm");
                xhttp[i].setRequestHeader("Content-Length", "37");
                xhttp[i].setRequestHeader("Connection", "keep-alive");
                xhttp[i].send('{"code":"'+code[i]+'","confirm":false}');
                p++;
            }
        })(i);
    }
}
</script>

</body>
</html>
Filip CZ
  • 179
  • 3
  • 12

2 Answers2

1

You are continuously spawning multiple calls to process() immediately in the while and then telling process to wait 5 seconds before that callback happens.

// Run this loop over and over again
while (true) {
    // Create a function called process that process data
    var process = (function () {
        // Do something with data
        console.log("Something");
        // Wait a few seconds and do it again
        setTimeout(process, 5000);
    // This () right here says call process right now
    }());
}
zero298
  • 25,467
  • 10
  • 75
  • 100
  • Thank You for your help, but could I ask you for the correction in my code? I still don't have much experience in JavaScript programming. – Filip CZ Aug 01 '16 at 16:18
  • I fixed the brackets in my code as you posted and I just kept the decrementing while loop, but script doesn't work now. I got this error in console: Uncaught TypeError: Cannot read property 'readyState' of undefined – Filip CZ Aug 01 '16 at 16:40
1

when you run your code, while loop won't wait for setTimeout because it is async.

but you can do following to make your code work.

var p = 0;
var k = 0;
var now = new Date();
var code = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var index = 0; index < code.length; index++) {
    (function(idx, timeout){
        setTimeout(function(i) {
            //write your code herei
            console.log("printed after", (new Date() - now)/1000, " Seconds");

        }, timeout, idx);
        p++;
        if(p==5){
            p = 0;
            k += 5000;
        }
    })(index, k);
}

Following is the output

printed after 0.006  Seconds
printed after 0.008  Seconds
printed after 0.008  Seconds
printed after 0.008  Seconds
printed after 0.008  Seconds
printed after 5.008  Seconds
printed after 5.008  Seconds
printed after 5.008  Seconds
printed after 5.008  Seconds
printed after 5.008  Seconds
printed after 10.007  Seconds
printed after 10.007  Seconds
printed after 10.007  Seconds
printed after 10.007  Seconds
printed after 10.007  Seconds
printed after 15.008  Seconds
printed after 15.008  Seconds
printed after 15.008  Seconds
printed after 15.008  Seconds
printed after 15.008  Seconds
suraj.tripathi
  • 417
  • 2
  • 15
  • Thank You suraj, I'll check your code immediatelly. – Filip CZ Aug 01 '16 at 16:42
  • EDIT: Well, it was just missing definition of k, but your script still doesn't work as I need. After 5 cycles through the loop, there must be a delay and this is not in your code. Btw thanks for your effort. Doesn't work man, Uncaught ReferenceError: k is not defined – Filip CZ Aug 01 '16 at 16:53
  • what are you trying exactly trying to do? make five continuous call then wait for 5sec and then make five more continuous call and so on? Or only every fifth call should be delayed by 5 sec – suraj.tripathi Aug 01 '16 at 16:57
  • EDIT 2: Well, every time I click the button after the preset delay post request is sent to server and I can see the response. But I need that script to automatically spawn and send request cycling through the loop and after for example 5 cycles - place a small delay. But requests must be send automatically, not after clicking a button. – Filip CZ Aug 01 '16 at 17:03
  • I could not test my solution as you did not share actual urls but still https://jsfiddle.net/xvLb54mL/ copy code from this link and paste it i think it will work – suraj.tripathi Aug 01 '16 at 17:24
  • Thanks for your time, i'll try it later. Thanks to your printed output it looks now more similar to the state I needed to achieve. – Filip CZ Aug 01 '16 at 19:42