Assuming you want the code inside the each
callback to have access to whatever value this
has when the setInterval
call is made, your code has two problems.
The first is that you're not bind
ing foo
itself. The code
setInterval(function(){
foo();
}.bind(this),5000);
successfully binds this
to the anonymous function function() { foo(); }
. This anonymous function then makes a direct call to foo
, which (in non-strict mode) sets the this
for the call to the global object window
or global
, as happens with any direct function call.
You need to explicitly pass on the anonymous function's this
to the foo
call inside the anonymous function with call
or apply
:
setInterval(function(){
foo.call(this);
}.bind(this),5000);
Now that foo
has the right this
, you need to make that this
value accessible inside of the each
callback. For that, you can consult How to access the correct `this` context inside a callback?, which will instruct you to store the outer this
in another variable. You simply store this
inside another variable and use that variable instead of this
inside the inner callback:
function foo() {
var outer_this_from_foo = this;
$('.rsContent').each(function(){
//here $(this) refers to selected div
//but outer_this_from_foo refers to the `this` value just outside this callback
var fI = $('>.img-responsive', outer_this_from_foo);
// instead of $('>.img-responsive', this)
});
};