Constantine Zafeirakis Constantine Zafeirakis - 2 months ago 16
Javascript Question

Infinite loop checker crashes - Jquery

So I wrote this short code for a small project of mine, here's the code:

while(true){


if(PremiumExchange.data.stock["wood"]>=64){

var x = PremiumExchange.data.stock["wood"];
document.getElementsByName('buy_wood')[0].value = x;
document.getElementsByClassName('btn float_right btn-premium-exchange-buy')[0].click();
document.getElementsByClassName('btn evt-confirm-btn btn-confirm-yes')[0].click();

}
}


Essentially "
PremiumExchange.data.stock["wood"]
" updates randomly after sometimes on the webpage. I'd like to set my code up so it keeps an eye on it and then does what I instructed it to.

Problem is, if I use an infinite loop, it hangs. Is there a way around this? Perhaps a timer of some sort?

Thanks in advance.

EDIT: I also tried

function wait(){
if (!(PremiumExchange.data.stock["wood"]>=64)){
setTimeout(wait,500);
} else {
var x = PremiumExchange.data.stock["wood"];
document.getElementsByName('buy_wood')[0].value = x;
document.getElementsByClassName('btn float_right btn-premium-exchange-buy')[0].click();
document.getElementsByClassName('btn evt-confirm-btn btn-confirm-yes')[0].click();
}
}


But it doesn't appear to work. Am I doing something wrong?

Answer

function test() {
  if (document.getElementById("test").value) {
    console.log("Success!");
    clearInterval(int);
  }
}

var int = setInterval(test,0);
<input id="test"></input>

This is an example of setting a test without causing a hang.

Optionally, clearInterval is included to make it only execute once.