views:

324

answers:

5

Hi,

I'm trying to use a jQuery statement inside a setTimeout function, but I don't get it to work. I tried a lot of variants, like this one (I'm using 'this' because the setTimeout is inside an each function, and the selector is cached/stored in an object, thus the $selector):

setTimeout("" + this.$selector + ".val('" + this.savVal + "')", 1);

How do I have to write this?

Thanks!

+1  A: 

You could probably do something like this, if the variables you are trying to use are defined in each step of the loop.

var myObj = {
  $selector: myConfigObj.$myCachedSelector
}

$.each([ myObj, mySecondObj, myThirdObj ], function(n, $selector) {
    setTimeout(function() {
     $selector.val(saveVal);
    }, 1);
});
Marco
Marco, "myConfigObj.$myCachedSelector" seems to be the problem. It returns "undefined". I replaced it with a simple string which gets returned correctly...
north
+7  A: 

When you need to preserve the current this item when calling setTimeout use this structure:-

setTimeout((function(self) {
  return function() { $selector.val(self.savVal) };
})(this), 1);

This creates a closure from the outer functions execution context. The outer function returns an inner function that will have access the self parameter. Its the inner function that gets called when the timeout occurs yet the value of self will hold on to the original this value.

AnthonyWJones
A: 

Hi all,

thanks for your answers.

I'm using a function inside the setTimeout now. But I found out that the real problem lies elswhere: in the each-function I'm trying to access object properties which are pointing to properties within a config object, but the result (for example for this.$selector) is "undefined".

var myObj = {
  $selector: myConfigObj.$myCachedSelector
}

$.each([ myObj, mySecondObj, myThirdObj ], function() {
    //code
});

Not sure what the problem is. Both objects are in the same function/scope.

north
A: 

I will post a new question with a more fitting title for this. Thanks again all!

north
+1  A: 

AnthonyWJones provided a great answer, but there's another similar one, which is slightly easier to write and read. You simply store the value of "this" in a local variable., ie.

var storedThis = this;
setTimeout(function() { $selector.val(storedThis.savVal); }, 1);
Evgeny