Reputation: 35
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
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
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