I have a jquery $.each loop feeding a different variable to a POST API call. I am trying to delay the API calls between each variable say 5 seconds, but it is executing all at the same time even with the setTimeout.
var skuList = require('../inputSKU.json');
const url = www.someurl.com
const query = `query example xyz`
//the problem below
$.each(skuList.list, function getData(i, e) {
var variables = e;
var body = JSON.stringify({
query,
variables
})
var resJSON = '';
var a = '';
setTimeout(async () => {
var res = await fetch(url,
{
method: 'POST',
body: body,
headers: {
'Content-Type': 'application/json',
'Content-Length': body.length,
"Accept": "application/json",
'x-gql-access-token': '8635be91-b771-11ed-aa31-49d35f4239b3',
'x-gql-country': 'US'
}
}
)
a = await res.json();
resJSON = a.data;
console.log(resJSON)
}, 5000);
});
This will rapid fire console.log the resJSON. Is there an elegant solution to adding the delay?
Seems there is a solution if I was using a for loop with an index.
for(var i in list) { // list is an array, i is current index
setTimeout(function() {
apicall()
}, 1500 * i) // With each iteration, the delay increases
}
Perhaps something like this for the $.each?