setTimeout() inside JavaScript Class using “this”

You can do this:

 var that = this;
 setTimeout(function () {
     that.doStuff();
 }, 4000);

You can also bind for more succinct code (as originally pointed out by @Raynos):

setTimeout(this.doStuff.bind(this), 4000);

bind is a standard library function for exactly this coding pattern (ie capturing this lexically).

Leave a Comment