How to stop waiting for an element when finding it (Javascript)

0

I have a question. I have the following code to wait for these elements and assign them those values. The problem is that the page is in loop thanks to the change event. I would like to know how to stop the timeout after having found those elements. Thanks!

function waitForElementToDisplay(selector, time) {
    if (document.getElementById(selector) != null) {
        document.getElementById(selector).value = "BM";
        document.getElementById(selector).dispatchEvent(new Event('change'));                   
        return;
    }
    else {
        setTimeout(function () {
            waitForElementToDisplay(selector, time);
            }, time);
        }
    }

waitForElementToDisplay('form1:layoutPanel1:layoutPanel2:tabSetDirecciones:tabDirPrincipal:layoutPanelDirPrincipal:drpDirTipo_list',100);
waitForElementToDisplay('form1:layoutPanel1:layoutPanel2:tabSetDirecciones:tabDirPrincipal:layoutPanelDirPrincipal:txtDirBarrioCK_field',100);
    
asked by Agustín Morelle 10.07.2018 в 04:39
source

1 answer

0

window.clearTimeout (timeoutID)

Simply use clearTimeout to remove the setTimeout created.

But to do that you will need to define a name for your timeout .

// Crear TimeOut
miTimeout = setTimeout();

// Eliminar TimeOut
clearTimeout(miTimeout)

Although I notice that your code is something strange (or is that I'm somewhat tired). If I have not misunderstood it, I think that what you are trying to do is to check if selector is null. If it is not, the main code block is executed, and if it is, a "loop" is created to try again later.

I think there are several ways to solve it, but at this moment it only occurs to me that you create a loop of truth setInterval() in which your function is found, and once it is completed you break the loop with clearInterval() .

Now I do not have time, but if you leave me a comment, I may remember something tomorrow.

    
answered by 10.07.2018 в 04:47