Reputation:
I have a function that is within a loop. I have a setTimeout
function around this function. My problem is that a variable which is being set is then getting overwritten because of the setTimeout (this needs to stay). Is there a simple way to fix this issue?
DEMO http://jsfiddle.net/L29yk2o6/
$("ul li").each(function(i, el) {
$this = $(this);
setTimeout(function () {
myFunct($this);
}, i*100);
});
function myFunct (item)
{
var myText = item.text();
$('body').prepend('<p>'+myText+'</p>');
}
Upvotes: 0
Views: 236
Reputation: 207501
That is what happens when you forget to use var
and create a global variable.
$this = $(this);
needs to be
var $this = $(this);
Upvotes: 2