Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i can create the function for the countdown in React native?

My skills in react native is basic, i want to create a basic countdown, when i click play the countdown start, like this example:

enter image description here

My Code:

render() {
return (

<Grid>
<Row>

<Col style={styles.col_exercise}>
<Image source={require('../../assets/images/done.png')} resizeMode="contain" style={styles.icon_videoexercise} />
<Text style={styles.titlecol_exercise}>Done</Text>
</Col>

<Col style={styles.col_exercise}>
<View style={{borderWidth: 2, borderColor: '#f39c12', borderRadius: 50, height: 100, width: 100,alignItems: 'center',
justifyContent: 'center'}}>
<Text style={{fontSize: 18, color: '#000'}}>
00:30
</Text>
</View>
</Col>

<Col style={styles.col_exercise}>
<Image source={require('../../assets/images/play.png')} resizeMode="contain" style={styles.icon_videoexercise} />
<Text style={styles.titlecol_exercise}>Play</Text>
</Col>

</Row>

</Grid>
);
}
like image 898
bdroid Avatar asked Dec 24 '22 07:12

bdroid


2 Answers

constructor(props) {
  super(props);
  this.state = { timer: 30 };
}

componentDidMount() {
 this.clockCall = setInterval(() => {
   this.decrementClock();
 }, 1000);
}

componentWillUnmount() {
 clearInterval(this.clockCall);
}

decrementClock = () => {      
 this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};

You can create a countdown with setInterval. Every second this.decrementClock() will be called after the component mounts. You will want to render this.state.timer in your render method.

constructor(props) {
  super(props);
  this.state = { timer: 30 };
}

startTimer = () => {
 this.clockCall = setInterval(() => {
  this.decrementClock();
 }, 1000);
}

decrementClock = () => {  
 if(this.state.timer === 0) clearInterval(this.clockCall)
 this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};

componentWillUnmount() {
 clearInterval(this.clockCall);
}

In render add the button with Onpress event listener.

<button Onpress={this.startTimer}> Play </button>

<Text style={{fontSize: 18, color: '#000'}}>
 {this.state.timer === 0 ? 'Times Up!' : {this.state.timer} }
</Text>
like image 157
Omar Avatar answered Dec 25 '22 21:12

Omar


To prevent negative numbers try this:

decrementClock = () => {  
  this.setState((prevstate) => ({ 
    timer: prevstate.timer-1 
  }), () => {
    if(this.state.timer === 0) {
      clearInterval(this.clockCall)
    }
  })
}
like image 43
Martin La Regina Avatar answered Dec 25 '22 21:12

Martin La Regina