Oxy157
Oxy157

Reputation: 35

Not run rest of code until said element exists

var choice1 = "hostAndPort";
var timer;

function clickerFunc() {
        timer = setInterval(checkElementExist(choice1), 500);
};

function checkElementExist(thing) {
     console.log("checkElementExist runs")
     advance = document.getElementById(thing);
     console.log(advance);
     if (advance == null){
        console.log("advance defined as null");
     } else{
        console.log("Free from loop");
        clearInterval(timer);
        clickerFunc2();
    }
};

function clickerFunc2() {
        console.log("woooooooooo");
};

So I've tried a suggestion below, but it still doesn't seem to work. clickerFunc is called when a button is pressed, console outputs:

checkElementExist runs
hostAndPort
null
advance defined as null

so clickerFunc2 is never called, and it does not seem to keep checking every 500 milliseconds.

UPDATE:

setInterval(function() { checkElementExist(choice1); },500);

done the trick. Thanks!

Upvotes: 0

Views: 52

Answers (2)

phts
phts

Reputation: 3925

Do not use while. It will hang up the browser.

Call your rest of code from checkElementExist

function checkElementExist(id) {
     console.log("checkElementExist runs")
     advance = document.getElementById(id);
     if (advance == null){
        console.log("advance defined as null");
     }
     else{
        console.log("Free from loop");
        clearInterval(timer);
        restOfCode();
    }
};

timer = setInterval(checkElementExist('hostAndPort'), 1000);

--- UPDATE ---

setInterval takes function as a first argument so it should be like: setInterval(checkElementExist, 1000);. The previous code just called your function once and interval did nothing.

Upvotes: 1

rmorrin
rmorrin

Reputation: 2495

In general, you can use return to 'not execute the rest of the code' in a function. It does seem as though there's an easier way around your problem though. What's the exact requirement?

function checkElementExist(id) {
     console.log("checkElementExist runs")
     advance = document.getElementById(id);
     if (advance == null){
        return;
     }

     // rest of logic here
};

Upvotes: 0

Related Questions