I am interacting with the webpage through chrome extension. I want to wait until an element (like a popup) comes up before continuing the interaction. I want to stop the execution of the function until the element appears because I am doing interacting in a sequential flow. Below is the example function I created. This function is not working as intended. It only delays the first iteration of the loop and the rest of the iterations of the loop are instant. So, the max time this function wait is 100ms as of now. How can I either fix this function or define an elegant way to wait.
function waitUntilElementLoad(elem, maxWaitInSec) {
for (let i = 0; i < maxWaitInSec *10; i++) {
if(elem) { return true;}
setTimeout(() => {console.log(i);}, 100);
}
return false;
}
Attempt2: (Following up on comments and answers)
async function waitUntilElementLoad(elem, maxWait) {
for (let i = 0; i < maxWait*10; i++) {
if(elem) { return true;}
console.log(i);
await timer(100); // then the created Promise can be awaited
}
return false;
}
if (await waitUntilElementLoad(popUpElemNextButton, 5)) {
console.log("Popup button appeared")
} else {
console.log("Popup button not appeared")
}
The waitUntilElementLoad function returns false even if the elements load up in 1 sec and the waiting time is 5 sec. If the element is already there before calling the function. it returns true. Could it be that the function does not receive updated DOM during its processing? Is there a way to handle this?