user3786924
user3786924

Reputation: 39

How to run a function continuously in RN

I am trying to create a sound metering app with React Native, but it seems that if I start the metering, which I have as a infinite loop until the user stops it, it hangs the app.

Basically the user taps a button, invokes startMonitor(), then the runMonitor starts and checkSound() does a check for the current decibel level.

The relevant code section here

startMonitor() {
    KeepAwake.activate();
    this.setState({ monitorStatus: true
    }, this.runMonitor );

  }

  runMonitor() {

    while(this.state.monitorStatus) {
      if(this.state.beginWait) {
       this.wait(5000);
     }

     if(!this.state.isTransmitting) {
        this.checkSound();
    } 
   }
  }

Any ideas on how to run a function continuously/infinite until the user cancels it?

Upvotes: 0

Views: 758

Answers (1)

SomoKRoceS
SomoKRoceS

Reputation: 3043

You can use setInterval:

startMonitor() {
     this.runMonitorIV = setInterval(runMonitor, 1000);
  }

  runMonitor() {

    while(this.state.monitorStatus) {
      if(this.state.beginWait) {
       this.wait(5000);
     }

     if(!this.state.isTransmitting) {
        this.checkSound();
    } 
   }
}


//called on user event
stopMonitor() {
  clearInterval(this.runMonitorIV);
}

(Not sure about your context or scope, but that's the basic idea)

There's also the TimerMixin that clears those timers triggers when a component unmounts.

Upvotes: 2

Related Questions