1

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.

1

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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);
})

1 Comment

Don't know why this is required, but worked but declaring the variable with jQuery() was the trick.
1

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.