I am attempting to execute a function after a delay of 1 second, but the function is triggered within an ajax call inside a foreach loop.
Code:
let index = 1;
portals.forEach(portal => {
setTimeout(() => {
$.ajax({
type: "POST",
url: url,
async: false,
success: function (data) {
index++;
text(index, total); // The goal is to call this function after a 1-second delay
}
});
}, 1000);
});
However, it only triggers at the first and last iteration.
I have attempted placing the function inside an asynchronous function and using a promise to solve the issue, but it still doesn't work. Here is the alternative code I tried:
let index = 1;
const delay = (amount = number) => {
return new Promise((resolve) => {
setTimeout(resolve, amount);
});
}
async function forPortals(){
for(index; index<=total; index++){
$.ajax({
type: "POST",
url: `/export/${portals[index].file}.php`,
async: false,
success: async function (data) {
if(index>total){
text(index, total);
await delay(1000);
}
});
}
}
forPortals();
- How can I trigger the
text()
function after a 1-second delay?
The desired outcome is for the function to be executed 7 times with a 1-second timeout each time.