hope you're doing well- I'm having some issues with getting a delayed loop going in JavaScript console. For context, I've been tasked with building a list of emails from our CRM, but the platform does not allow export of this data beyond listing it all in a search.
I've created a blank array to push emails to, we'll worry about getting this data out after.:
emailsList = [];
So I need to the following for each row of the table:
function clickPopup() {
//Click User Code to Trigger Ajax Popup
document.querySelector("#tblReport > tbody > tr:nth-child(" + i + ") > td:nth-child(2) > a").click();
}
function getEmailTextAndClose() {
// Grab Dom Content in email variable
var email = document.querySelector("#email_compose_link").innerText;
// Push email to emailList array
emailsList.push(email);
parent.parent.$.fn.colorbox.close()
}
these all work fine, but where I'm struggling is in putting these into a loop with a delay, the popup needs a second to pull the content via ajax. So what I've tried:
emailsList = [];
function clickPopup() {
//Click User Code to Trigger Ajax Popup
document.querySelector("#tblReport > tbody > tr:nth-child(" + i + ") > td:nth-child(2) > a").click();
}
function getEmailTextAndClose() {
// Grab Dom Content in email variable
var email = document.querySelector("#email_compose_link").innerText;
// Push email to emailList array
emailsList.push(email);
parent.parent.$.fn.colorbox.close()
}
for(var i = 0; i < 100; i++) {
setTimeout(function() {
// after 1000ms, call the `setTimeout` callback
// In the meantime, continue executing code below
setTimeout(function() {
getEmailTextAndClose() //runs second after 11000ms
},1000)
clickPopup() //runs first, after 10ms
},10)
}
And:
emailsList = [];
function getEmailTextAndClose() {
// Grab Dom Content in email variable
var email = document.querySelector("#email_compose_link").innerText;
// Push email to emailList array
emailsList.push(email);
parent.parent.$.fn.colorbox.close()
}
for(var i = 0; i < 100; i++) {
clickPopup(i);
}
function clickPopup(i) {
setTimeout(() => {
document.querySelector("#tblReport > tbody > tr:nth-child(" + i + ") > td:nth-child(2) > a").click();
setTimeout(getEmailTextAndClose() 2000)
}, 2000);
getEmailTextAndClose();
}
All these configurations either dont delay the second function, or dont increment the i's in our query selector. Am I going about this all wrong?
Many thanks.
Try using a promise with the code that triggers the ajax function: