If selector exists - run code else repeat check
I'm trying to check if a selector exists, if it does I would like it to run some code, if it doesn't I would like it to repeat the check.
The reason I want to do this is because I know an elemen开发者_如何转开发t WILL exist, but I will not know when.
Something like this:
if ($(.element).length ) {
// Do something
}else{
//check again
});
Any ideas?
var interval = setInterval(function () {
if ($(".youtube5player").length) {
clearInterval(interval);
// Do stuff
}
}, 100);
What this does is use setInterval
to perform a check approximately every 100 ms to see if your selector returns any results. If it does, the interval is cleared and the code will not run again.
Example: http://jsfiddle.net/rBdFP/
Besides using setInterval you can also use a recursive setTimeout pattern like the following:
(function doCheck(){
setTimeout(function(){
if ($(.element).length ) {
// Do something
}else{
//check again
doCheck();
});
}, 100);
})();
While it doesn't seem likely in your case see there are times where using setInterval is considered harmful. From the documentation:
If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using window.setTimeout. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its alloted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.
For such cases, a recursive setTimeout pattern is preferred
精彩评论