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!
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.
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.
Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With