最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Variables in a setTimeout function (jQuery) - Stack Overflow

programmeradmin2浏览0评论

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!

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!

Share Improve this question asked Nov 4, 2009 at 12:59 northnorth 6058 silver badges22 bronze badges 1
  • 3 Strings in setTimeout() and setInterval() are obsolete. Functions should be used instead. – Robert Koritnik Commented Nov 4, 2009 at 13:04
Add a comment  | 

4 Answers 4

Reset to default 19

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 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);

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);
});

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.

发布评论

评论列表(0)

  1. 暂无评论