1

I have a ajax like as below:

$.get('/api/get-data)
.then(function (res) {
 console.log(res);
});

And i want write a loop to get data, like this:

while (true) {
 $.get('/api/lastbids/' + auctionId)
 .then(function (res) {
 console.log(res);
 });
}

I want set delay between every request, i can use setinterval but i want when get response finished, after 500ms send another request for data.

asked Apr 29, 2019 at 10:07
4
  • Use promises developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… so you can track whether you got the response or not. Commented Apr 29, 2019 at 10:10
  • 1
    @divakar what is .then() in jQuery? Commented Apr 29, 2019 at 10:10
  • 1
    Create a function to get /api/lastbids/, than in callback delay 500ms, than call same function again. Commented Apr 29, 2019 at 10:13
  • @RokoC.Buljan Since he want it to be deferred, i suggested a custom promise function. Commented Apr 29, 2019 at 10:16

2 Answers 2

2

You could use a simple function recursion with a recurring setTimeout:

function getBidsLoop () {
 $.get('/api/lastbids/' + auctionId).then(function (res) {
 console.log(res);
 setTimeout(getBidsLoop, 500); // << Recursive call
 });
}
getBidsLoop (); // Start
answered Apr 29, 2019 at 10:18
Sign up to request clarification or add additional context in comments.

2 Comments

i used your code, and set 1 sec delay in backend (/api/las..) but only work in first time, please check it i.imgur.com/Xvc0gG5.png
@Masoud92m fixed. Sorry, my mistake
0

You can use callbacks for each request

var firstRequest = function(callback) {
 // some random endpoint for result
 $.get('https://pokeapi.co/api/v2/pokemon/1/', function(data) {
 callback(data);
 }).fail(function() {
 callback(false);
 });
 },
 secondRequest = function(callback) {
 // some random endpoint for result
 $.get('https://pokeapi.co/api/v2/pokemon/2/', function(data) {
 callback(data);
 }).fail(function() {
 callback(false);
 });
 };
// first, run first request, wait for response, then run second request. finally grab both request's responses. 
firstRequest(function(firstResult){
 if (firstResult) {
 // you can wrap the code below with setTimeout if you want
 secondRequest(function(secondResult) {
 console.log(firstResult, secondResult);
 });
 }
});
answered Apr 29, 2019 at 13:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.