jQuery/Javascript: setInterval check if DOM element exists?
-
25-09-2019 - |
Question
var check; function showLoader() { $('#mc_signup_form').prepend(' loading …'); check_init(); }
function check_init() {
check = setInterval('check_trigger()', 300);
}
function check_clear() {
clearInterval(check);
}
function check_trigger() {
if ( $('.mc_error_msg').length == 0 || $('.mc_success_msg').length == 0 ) {
$('#mc_signup_form .loading').remove();
check_clear();
}
}
i wonder why my browser keeps telling me that check_trigger() doesn't exist? I'm initiating a setInterval inside of my showLoader() function. It should trigger check_trigger. When one of the two divs (.mc_error_msg or .mc_success_msg) exists i want to clear the Interval.
What am I doing wrong?
Solution
I find passing strings to setTimeout
and setInterval
just leads to problems :)
Try:
setInterval(check_trigger, 300);
OTHER TIPS
it should be check_trigger only remove outside the single or double quote...
also use setTimeout instead of setInterval so you can get rid of the global variable
Avoid double evaluation
By putting that function into quotes
, ECMA-/Javascript will eval
that code, which is just unbelievable slow'ish. So always use a function reference
withing setTimeout
/ setInterval
:
setInterval(function(){
check_trigger();
}, 300);
or directly
setInterval(check_trigger, 300);
If you remove the elements in question by yourself somewhere, it might be an interesting approach to hook the jQuery .remove()
or .detach()
method (If you call those to remove the element).
That could look like:
var hookRemove = $.fn.remove;
$.fn.remove = function(){
if(this.id === 'something'){
// hoorray! we found it
}
hookRemove.apply(this, arguments);
};
Remember your're dealing with an jQuery object
within the hook. So actually this
could also be a wrapped set
of elements. Therefore a call to
this.each(function(){
});
within the hook should be more save for checking. That way you have an exact
knowledge of when an object is removed without an intervall timer
.
Combining the various suggestions here is as simplified version which should work regardless of the scope in which it is defined.
function showLoader () {
$('#mc_signup_form').prepend('<span class="loading"> loading …</span>');
setTimeout (function check_trigger () {
if ( $('.mc_error_msg').length == 0 || $('.mc_success_msg').length == 0 ) {
$('#mc_signup_form .loading').remove();
} else {
setTimeout (check_trigger, 300);
}
}, 300);
}