Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout() inside JavaScript Class using "this"

I am trying to use setTimeout() inside a class function in JavaScript. The setTimeout() is supposed to trigger another method in the same Class, so the function I am passing it is written as window.setTimeout("this.anotherMethod", 4000). That bring the problem: this references the calling Object, in the case of setTimeout() it is window. How can I use enclosures to return a reference to the Class Object itself?

myObject = function(){  this.move = function(){     alert(this + " is running"); } this.turn = function(){     alert(this + " is turning"); } this.wait = function(){     window.setTimeout("this.run" ,(1000 * randomNumber(1,5))); }  this.run = function(){     switch(randomNumber(0,2)){         case 0:             this.move();         break;         case 1:             this.turn();         break;         case 2:             this.wait();     } } 

}

like image 591
Dean Avatar asked May 06 '11 12:05

Dean


People also ask

What is the use of setTimeout () in JavaScript?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

What is the alternative for setTimeout in JavaScript?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.

Is setTimeout part of JavaScript?

setTimeout and setInterval are not actually included in javascript - let's understand this. Maybe you think setTimeout like this -: The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.


2 Answers

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).

like image 73
Tikhon Jelvis Avatar answered Sep 19 '22 04:09

Tikhon Jelvis


You can also bind a function to scope.

setTimeout(this.run.bind(this) ,(1000 * randomNumber(1,5)));

Be warned Function.prototype.bind is ES5

like image 32
Raynos Avatar answered Sep 19 '22 04:09

Raynos