Nick Blexrud
Nick Blexrud

Reputation: 9603

Passing jQuery object into setTimeout recursive function

I'm attempting to pass in a jQuery object into a setTimout function, but to no avail.

This is what I currently have - It's working:

var checkIfElementsExist = function () {

    var elements = $('.myElements');

    if (elements.length) {
        console.log('els are here!');
        $(window.document).trigger('elementsExist', [elements]);

    } else {
        console.log('nope, check it again');
        setTimeout(checkIfElementsExist, 500);
    }

}

checkIfElementsExist();

But as soon as I take $('.myElements') out of the function, and try passing it into the function as an argument, elements.length always returns zero.

var checkIfElementsExist = function (elements) {

    if (elements.length) {
        console.log('els are here!');
        $(window.document).trigger('elementsExist', [elements]);

    } else {
        console.log('nope, check it again');
        setTimeout(checkIfElementsExist, 500);
    }

}

checkIfElementsExist($('.myElements'));

I read that you cannot pass in arguments into the setTimeout function, so I attempted to pass elements as an additional argument into the setTimeout call e.g. setTimout(checkIfElementsExist, 500, elements);, but still nothing.

UPDATE:

I've made the update that Pointy mentioned, but it still appears to not work. Here is a JSFIDDLE to better illustrate the problem.

Upvotes: 2

Views: 176

Answers (2)

lyjackal
lyjackal

Reputation: 3984

Executing $('.myElements') traverses the DOM and returns an array of all elements with class="myElements".

When you pass $('.myElements') initially, you are only constructing that array the first time. The following proceeding times you are not passing any arguments.

The real question here is why are .myElements not loaded when your script is loaded? Are they created dynamically? If not, your script should be wrapped in $(document).ready(function(){ // ... code here }) to wait for the full page to be loaded.

Upvotes: 1

Pointy
Pointy

Reputation: 413720

Instead of

    setTimeout(checkIfElementsExist, 500);

you can do this:

    setTimeout(function( ) { checkIfElementsExist(".myElements"); }, 500);

By wrapping an anonymous function around your actual function, you can pass in whatever arguments you want.

Upvotes: 5

Related Questions