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
Masoud92m
6221 gold badge9 silver badges24 bronze badges
2 Answers 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
Roko C. Buljan
209k41 gold badges335 silver badges347 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Masoud92m
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
Roko C. Buljan
@Masoud92m fixed. Sorry, my mistake
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);
});
}
});
Comments
lang-js
.then()in jQuery?/api/lastbids/, than in callback delay 500ms, than call same function again.