krishna swaroopa I
krishna swaroopa I

Reputation: 371

setTimeout is freezing my app in react native

I am using setTimeout function to show 3.. 2.. 1.. Go text before starting my actual functionality

But sometimes the app get freezes at 2 or 1 or GO and directly jumping to the actual functionality.

my code is as follows:

  setInterval(() => {
      _this.setState({
        timer: _this.state.timer - 1
      })
      if (_this.state.timer == 0) {
        _this.setState({ timer: 'GO' })
      }
    }, 1000)

So for every second the timer reduces its value when it is 0 its shows GO But my app is getting freezes Can anyone help me in solving this Thanks

Upvotes: 3

Views: 1613

Answers (3)

Jeeva
Jeeva

Reputation: 1590

You can use like this. Since both the setInterval and setState were asynchronous.

let timer = this.state.timer
let interval = setInterval( () => {
  if(typeof timer === "number"){
    timer--;
  }
  if(timer === 0){  //once the timer goes 0 then it clears interval
    clearInterval(interval)   //to clear Interval
    this.setState({ timer: "Go"})
  }else{           
    this.setState({ timer: timer})
  }      
}, 1000)

Upvotes: 1

Daniel Adepoju
Daniel Adepoju

Reputation: 821

setInterval(() => {
      _this.setState({
        timer: _this.state.timer - 1
      })
      if (_this.state.timer == 0) {
        _this.setState({ timer: 'GO' })
      }
    }, 1000)

You need to know that setState is an asynchronous function and sometimes, as at the point of your if statement, the value of timer is might not be changed.

For explanation, consider this:

// assuming this.state = { value: 0 };
this.setState({ value: this.state.value + 1});
this.setState({ value: this.state.value + 1});
this.setState({ value: this.state.value + 1});

After all the above calls are processed this.state.value will be 1, not 3 like we would expect!

I'll suggest you reframe your function to be:

setInterval(() => {
  let prevtime = this.state.timer
  this.setState({
    timer: prevtime - 1
  })
  if (prevtime - 1 == 0) {
    this.setState({ timer: 'GO' })
  }
}, 1000)

For more details on setState and async function visit here

Upvotes: 1

Santosh Sharma
Santosh Sharma

Reputation: 2248

As per your code you are using setInterval not setTimeout. you need to clear interval. clearInterval()

Upvotes: 0

Related Questions