jquery - Javascript SetInterval Help. Ajax -


this question has answer here:

i trying make code website

function vind(list) {     (i = 0; < list.data.length; i++) {         jquery.ajax({             url: 'https://xyz-abc.com/send.php?post=123',             datatype: 'script',             success: function () {                 volve += 1;                 if (volve >= list.data.length) {                 }             }         });     } } 

all code working fine.

https://xyz-abc.com/send.php?post=123 https://xyz-abc.com/send.php?post=123 https://xyz-abc.com/send.php?post=123 https://xyz-abc.com/send.php?post=123 

code posting continous.

i want set interval between each post.

https://xyz-abc.com/send.php?post=123 wait 3 sec. https://xyz-abc.com/send.php?post=123 wait 3 sec. https://xyz-abc.com/send.php?post=123 wait 3 sec. 

i tried settimeout not working.

help.

if first want wait previous request complete can send 1st item , use settimeout trigger request on rest of list.

function vind(list) {    if (list.length > 0) { // stop if list empty      var firstitem = list.shift(); // nothing done this?      jquery.ajax('https://xyz-abc.com/send.php?post=123', {        datatype: 'script',        success: function() {          settimeout(function() { // set timeout function call senddata again            senddata(list); // call senddata rest of list          }, 3000); // 3 seconds        }      });    }  }

you can check working plnkr of here.

if not want wait previous requests complete can use settimeout set bunch of timeouts different delays. not recommend doing large lists though.

function senddata(item) {    console.log(date.now());    jquery.ajax('https://xyz-abc.com/send.php?post=123', {      datatype: 'script',      success: function() {}    });  }    function vind(list) {    (var = 0; < list.length; i++) {      var currentitem = list[i]; // saving item in current scope now, in case list gets modified in meantime      settimeout(function() {        senddata(currentitem);      }, * 3000); // delay depends on item's index in list    }  }
, working plnkr of solution here.

keep in mind though settimeout not guarantee set function called @ 3 seconds mark. place function in callback queue after 3 seconds have passed. means because of way javascript concurrency works won't able function called @ 3 seconds mark using settimeout.

you can find explanation on how event loop works here. there's tool made same guy gives visual representation of going on behind scene here.


Comments