Calling a class prototype method by a setInterval event

All the answers above are acceptable. I just wanted to add that the binding of this can also be solved by using an arrow function. For example, these are all equivalent to each other. However, the lexical scope is maintained when using arrow functions:

 // Arrow function - my preferred method
 loadingTimer = setInterval(() => this.showLoading, 100);

 // .bind method
 loadingTimer = setInterval(this.showLoading.bind(this), 100);

 // Other method
 var t = this;
 loadingTimer = setInterval(function(){t.showLoading();}, 100);

Hope this helps :D


loadingTimer = setInterval("this.showLoading()", 100);

Firstly, don't use string arguments to setInterval/Timeout. It's dodgy in the same way as using eval, and may similarly fail with CSP security restrictions in the future. So instead:

loadingTimer = setInterval(this.showLoading, 100);

However, as you say, this will lose the owner reference so the called function won't see the right this. In the future (the newly-defined ECMAScript Fifth Edition), you will be able to bind the function to its owner with function.bind:

loadingTimer = setInterval(this.showLoading.bind(this), 100);

and if you implement function.bind yourself for browsers that don't yet have it (see the bottom of this answer), you can use this syntax today.

Otherwise, you will need to use an explicit closure, as in the example Computer Linguist just posted.


setInterval can take a function directly, not just a string. https://developer.mozilla.org/en/DOM/window.setInterval

i.e.

loadingTimer = setInterval(showLoading, 100);

But, for optimal browser compatibility, you should use a closure with an explicit reference:

 var t = this;
 loadingTimer = setInterval(function(){t.showLoading();}, 100);

Tags:

Javascript