Issues with setTimeout() inside jQuery .each

后端 未结 5 765
猫巷女王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:13

    The first parameter to setTimeout (or setInterval) needs to be a reference to a function (or a string, but you don't want to use the string syntax).

    Instead of passing a function as a parameter you are calling a function and passing its result. If you remove the parentheses you'll pass a reference to the function:

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

    But then you'll start having trouble with this being the wrong thing at the time the function actually runs. Try something like this:

    var i = 1,
        timer = [];
    jQuery('a').each(function($) {
        i++;
        var $this = jQuery(this);
        timer[i] = setTimeout(function() {$this.remove();}, i * 5000)
    })
    

    This takes advantage of the way closures work in that the anonymous function passed to setTimeout will have access to the $this variable at the time it is run even though the function in which $this is declared will have finished executing by then.

    Note that it is better to declare arrays with [] than new Array().

    Note also that you initialise i to 1, then increment it before using it such that the first element that you add to your array will be timer[2]. You probably should initialise it to 0 and then increment it after setting each timer.

提交回复
热议问题