How to use “setTimeout” to invoke object itself

Try replacing this line:

setTimeout('this.feedbackTag.removeChild(info)', 5000);

with these two lines:

var _this = this;
setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000);

Note:

Never pass setTimeout a string, as this invokes eval (which you should only use when necessary). Instead, pass setTimeout a function reference (this can be an anonymous function).

Finally, always check that the this keyword is pointing to what you think it points to (see http://www.alistapart.com/articles/getoutbindingsituations).

Addressing Question 2:

I believe that for normal functions, this is set to the window object—regardless of where they are declared. So moving the code into a separate function wouldn’t fix the problem.

Leave a Comment