Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in a setTimeout function (jQuery)

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!

like image 949
north Avatar asked Nov 04 '09 12:11

north


People also ask

How do you pass arguments in setTimeout?

The setTimeout() Method To repeat execution, use the setInterval() method. The returned value timeoutID is a positive integer that identifies the timer which is created by the call to the setTimeout() method. The value can be passed to clearTimeout() to prevent the function from executing.

What value is returned by setTimeout ()?

Return value The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout() . This value can be passed to clearTimeout() to cancel the timeout.

How many parameters does a setTimeout f unction accept?

Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period.


2 Answers

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.

like image 108
AnthonyWJones Avatar answered Sep 25 '22 17:09

AnthonyWJones


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);
like image 28
EMP Avatar answered Sep 25 '22 17:09

EMP