TypeScript setTimeout loop passing this error

↘锁芯ラ 提交于 2020-11-27 04:55:44

问题


Trying to create a timer loop in TypeScript:

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

But after the first loop works correctly I'm getting this error: "Uncaught TypeError: this.timeout is not a function". It seems that the this variable does not exist after the initial loop. Any ideas?


回答1:


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();



回答2:


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

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


来源:https://stackoverflow.com/questions/41763518/typescript-settimeout-loop-passing-this-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!