americanknight
americanknight

Reputation: 759

setTimeout() function doesn't work inside of jQuery each() function

I want to apply code to a series of matched elements with a delay between each. I don't understand why the following code doesn't work:

        jQuery(".myElement").each(function() {
            setTimeout(function() {
                jQuery(this).remove();
            }, 1000);
        });

I know there's been similar questions asked, but the answers haven't worked for me. I understand that this code is simultaneously applying the delays to each matched element, which isn't what I want. But I still can't figure out how to make it work.

Upvotes: 1

Views: 2715

Answers (3)

americanknight
americanknight

Reputation: 759

Thanks for the answers. For whatever reason, I couldn't get either of them to work. This code, however, ended up doing the job for me:

jQuery(".element").each( function(e) {
    var element = jQuery(this);
    setTimeout(function () {
        jQuery(element).remove();
    }, e*1000);
});

Upvotes: 1

mohamedrias
mohamedrias

Reputation: 18566

JSBIN DEMO

Your issue lies in the fact that you are invoking jQuery(this).remove() and passing the return value of this to your setTimeout. The assumption is that you are intending for this to run when the timeout expires. If that is the case, you need to wrap this in a function, so that function will be passed to setTimeout and executed when the timer expires.

jQuery('.myElement').each(function() {
    var thiz = jQuery(this);
    setTimeout(function() { thiz.remove(); }, 1000);
})

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

No need for .each

setTimeout(function() {
    jQuery(".myElement").remove();
}, 1000);

The reason for now working is because this no longer refers to the element in each -- you could set a context variable, but since you're just removing the elements anyway, just do it in one swoop!

Upvotes: 2

Related Questions