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 recei
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