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.

americanknight
  • 689
  • 3
  • 18
  • 37
  • possible duplicate of [How to add pause between each iteration of jQuery .each()?](http://stackoverflow.com/questions/5202403/how-to-add-pause-between-each-iteration-of-jquery-each) and [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196). – Felix Kling May 08 '14 at 23:57

3 Answers3

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!

tymeJV
  • 103,943
  • 14
  • 161
  • 157
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);
})
mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • Don't know why this is required, but worked but declaring the variable with jQuery() was the trick. – elPastor Jun 05 '18 at 19:50
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);
});
americanknight
  • 689
  • 3
  • 18
  • 37