Search code examples
javascriptgoogle-chrome-extensionmutation-observersbrowser-extension

Pause javascript for-loop while waiting for response from mutation observer?


This is maybe an unusual situation, but I'm writing a Chrome extension that iterates through elements on a webpage. To do this, I'm going through the children of the main div using a for-loop, like below:

function grab_data() {
    //element in the DOM which contains the transcript history
    var parent_elem = document.querySelector("#yDmH0d > c-wiz > div > div.jkOv3d > c-wiz:nth-child(4) > c-wiz > c-wiz > div > div:nth-child(1)");
    for (let i = 0; i < (parent_elem.children.length); i++) {
        if (parent_elem.children[i].hasAttribute("data-timestamp")) {
            //regular case, handle data normally
            some_code();
        }
        else {
            // this is the special case, click a button and the mutation observer will be triggered
            example_button.click();
        }

In the else block, I need to wait for data that is grabbed in the callback function of the mutation observer before continuing on to the next iteration of the loop. Is this possible? How can I go about doing this?


Solution

  • That behavior can be achieved using promises.

    function asyncFunction(i){
        setTimeout(() => {
                console.log(i);
            }, 500 * i);
    }
    
    async function mainLoop() {
        for(let i = 0; i < 10; i++){
           await asyncFunction(i);
        }
    }
    
    mainLoop()

    Where asyncFunction is your callback.

    That way your main loop will wait until the callback is resolved. I am not sure if this is a good practice, though.