why is this returning undefined for all ID’s?
var time = 200;
$('.block').each(function () {
setTimeout(function () {
console.log($(this).attr('id'));
}, time);
time += 200;
});
but this returns the ID’s just fine?
var time = 200;
$('.block').each(function () {
console.log($(this).attr('id'));
setTimeout(function () {
}, time);
time += 200;
});
I’m trying to create a sort of bubbling in one at a time effect and this is driving me crazy
The value of
thisinside the callback (the global object) is not the same as in the outer scope (where it’s the current element). Use the following to close over a reference to the correct value:This works because the function passed to
setTimeoutis a closure that retains access to the variables declared in its lexical scope (which includesthat).The general lesson here is that the value of
thisinside a function is determined dynamically and depends entirely on how the function was executed:thisto the current element (usingcall/apply).The browser executes the inner function in a global context, which is why the value of
thisiswindowthere. This simple test demonstrates that last point:In modern browsers, an alternative to the solution above is to use
bind: