Calling a class prototype method by a setInterval event

前端 未结 3 1097
甜味超标
甜味超标 2020-12-14 00:57

I have a simple javascript class.

One method of this class sets up a timer using setInterval function. The method that I want to call every time the event fires is

3条回答
  •  一向
    一向 (楼主)
    2020-12-14 02:01

    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

提交回复
热议问题