Issues with setTimeout() inside jQuery .each

后端 未结 5 821
猫巷女王i
猫巷女王i 2021-01-21 06:33

The following code will not work properly. I\'ve tried different variations & searching everywhere but no luck.

i = 1;
var timer = new Array();
jQuery(\'a\')         


        
5条回答
  •  情深已故
    2021-01-21 07:11

    Felix has already hinted at the issue in the comments, but I will expand.

    timer[i] = setTimeout(jQuery(this).remove(), i * 5000)
    

    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.

    var $el = jQuery(this);
    
    timer[i] = setTimeout(function(){
        $el.remove()
    }, i * 5000)
    

提交回复
热议问题