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\')
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.