i am trying to make a delay in my ajax data so the loop become a little bit slower ! and here is my code
JavaScript
x
13
13
1
$(document).ready(function (){
2
$('#button').click(function(){
3
4
$('#hide').show();
5
var data = $('#textarea').val();
6
7
var arrayOfLines = data.split("n");
8
9
var track = JSON.stringify(arrayOfLines);
10
var item = "";
11
12
var lines = $('#textarea').val().split('n');
13
here is the loop
JavaScript
1
17
17
1
for (var i = 0; i < lines.length; i++) {
2
item = lines[i];
3
$.ajax({
4
type: 'GET',
5
url: 'cookie.php',
6
dataType: 'html',
7
data: 'data=' + item+'&cookie='+track,
8
success: function(msg){
9
$('#results').append(msg);
10
11
}
12
13
});
14
}
15
16
});
17
Advertisement
Answer
Using recursion, you could put in a function sendToServer
and pass through the array lines
, starting index 0. The function will run from 0 to lines.length. This way you won’t DDOS your server 🙂
If you really need some kind of arbitrary delay, you can include a timeout on the sendToServer
function call – in the example it is set to 5 seconds.
JavaScript
1
23
23
1
var sendToServer = function(lines, index){
2
if (index > lines.length) return; // guard condition
3
item = lines[index];
4
if (item.trim().length != 0){
5
$.ajax({
6
type: 'GET',
7
url: 'cookie.php',
8
dataType: 'html',
9
data: 'data=' + item+'&cookie='+track,
10
success: function(msg){
11
$('#results').append(msg);
12
setTimeout(
13
function () { sendToServer(lines, index+1); },
14
5000 // delay in ms
15
);
16
}
17
});
18
}
19
else { sendToServer(lines, index+1); }
20
};
21
22
sendToServer(lines, 0);
23