Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

javascript - How access object which created interval from interval callback?

I am new to JavaScript and coming not forth with my current issue. I have here an React App and I try to expand it by a timer functionality. I created a timer (similar to this question: setInterval in a React app) and the timer functionality itself is working.

But the timer callback (or more exactly the setInterval callback) is not working. In the setInterval the variable this is pointing to Windows but I thought it should point to App, which is the class/object who created the timer and contains the setInterval callback. Therefore I get following error.

enter image description here

Here are the crucial code changes I made:

class App extends Component {

  //...

  componentDidMount() {

    //...

    var intervalId = setInterval(this.timer, 5000);
    // store intervalId in the state so it can be accessed later:
    this.setState({intervalId: intervalId});
  }

  componentWillUnmount() {
    
    //...

    // use intervalId from the state to clear the interval
    clearInterval(this.state.intervalId);
  }

  timer() {
    for (let i = 0; i < this.state.whitelist.length; i++) {
      this.requestDeviceStatus(this.state.whitelist[i]);
    }
  }

 //...

}

But you can access the complete source code/commit here: https://github.com/wewa00/Reacticz/blob/backgroundtimer/src/App.js, (And this are the Relevant commits: 02e3e93, 6bcabba.)

Why this pointing to Window and how can I access App from within timer()?

question from:https://stackoverflow.com/questions/65860190/how-access-object-which-created-interval-from-interval-callback

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

TypeError

Use timer function with ES6 arrow method.

timer=()=>{
   for (let i = 0; i < this.state.whitelist.length; i++) {
        this.requestDeviceStatus(this.state.whitelist[i]);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...