views:

320

answers:

1

How do I pass context into setTimeout? I want to call this.tip.destroy() if this.options.destroyOnHide after 1000 ms. How can I do that?

if (this.options.destroyOnHide) {
     setTimeout('this.tip.destroy()', 1000);
} 

When I try the above, "this" refers to the window.

+6  A: 

You need to save a reference to the context where the setTimeout function call is made, because setTimeout executes the function with this pointing to the global object:

var that = this;
if (this.options.destroyOnHide) {
     setTimeout(function(){that.tip.destroy()}, 1000);
} 

You can easily prove that setTimeout set this to the global object by:

(function () {
  alert(this); // alerts hello
  setTimeout(function(){
    alert(this == window); // true
  }, 1000);
}).call("hello");

See also:

CMS
It works. I tested the concept with a jsbin script: http://jsbin.com/etise/7/edit
John K