tags:

views:

37

answers:

1

I'm seriously struggling today.

I need to pass a variable, or even better an object, into a timeOut as such (example) :

$('.x').each(function() 
{
  setTimeout(function()
  {
    alert ($(this).attr('id'))
  },10000);
});

Obviously what happens is that the timeOut doesn't have reference to the original $(this)

Help ?

+3  A: 

this is context sensitive (and is different in a_jQuery_object.each than it is in window.setTimeout, but its reference can be copied to a different variable that is not context sensitive. It is conventional to use that for this purpose.

$('.x').each(function() {
    var that = this; 
    setTimeout(function() { 
        alert ($(that).attr('id'))
    },10000); 
});
David Dorward
Worked. I don't get why though. Surely the setTimeout is also outside the scope of the parent function so it would lose the var ?
Bob
The function was created in the same scope that `that` was created in, so it keeps access to those variables.
David Dorward
Got it. Thank you very much for your help. I missed the point that it was at the point where it was created rather than executed.
Bob