TypeScript setTimeout loop passing this error

前端 未结 2 1714
陌清茗
陌清茗 2021-01-04 05:21

Trying to create a timer loop in TypeScript:

timeout() {
    setTimeout(function () {
        console.log(\'Test\');
        this.timeout();
    }, 1000/60);         


        
相关标签:
2条回答
  • 2021-01-04 05:34

    Because of this context is lost. Use the arrow function this is better.

    timeout() {
        setTimeout(() => {
            console.log('Test');
            this.timeout();
        }, 1000/60);
    }
    
    0 讨论(0)
  • 2021-01-04 05:41

    Because your this doesn't refer to the object. Every function has it's own this. So your this is the one which is defined by anonymous function inside the setTimeout().

    To make your program work, you need to hold the this before the timeout and use throught that variable.

    class Test {
      
      timeout() {
          var that = this;
          setTimeout(function () {
              console.log('Test');
              that.timeout();
          }, 1000/60);
      } 
      
    }
    
    
    let t = new Test();
    t.timeout();

    Or you can work with lambda functions, which will keep the this to your object.Lamda's this will refer to the outer's this, which call the lambda function`.

    class Test {
          
       timeout() {
           setTimeout(() => {
               console.log('Test');
               this.timeout();
           }, 1000/60);
       } 
          
    }
    
    
    let t = new Test();
    t.timeout();

    0 讨论(0)
提交回复
热议问题