views:

183

answers:

5

hey guys,

    var check;
    function showLoader() {
        $('#mc_signup_form').prepend('<span class="loading"> loading &hellip;</span>');
        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?

+1  A: 

it should be check_trigger only remove outside the single or double quote...

KoolKabin
A: 

I find passing strings to setTimeout and setInterval just leads to problems :)

Try:

setInterval(check_trigger, 300);
sje397
Yeah, just pass the function directly :)
airmanx86
+1  A: 

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.

jAndy
+1  A: 

also use setTimeout instead of setInterval so you can get rid of the global variable

john_doe
A: 

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 &hellip;</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); 
}
Hans B PUFAL