- setTimeout,clearTmeout
- setInterval,clearInterval
在 class 中
class TimersDemo extends Component {
constructor(props) {
super(props);
this.state={
content:'',
}
}
componentDidMount() {
this.timer = setTimeout(
() => {
this.setState({content:'我是定时器打印的内容...One'})
},
500
);
this.timer_two = setTimeout(
() => {
this.setState({msg:'我是定时器打印的内容...Two'})
},
1000
);
}
componentWillUnmount() {
this.timer && clearTimeout(this.timer);
this.timer_two && clearTimeout(this.timer_two);
}
render() {
return (
<View style={{margin:20}}>
<Text style={styles.welcome}>
定时器实例
</Text>
<Text>{this.state.content}</Text>
<Text>{this.state.msg}</Text>
</View>
);
}
}
setTimeout 延时的定时执行
<CustomButton text='测试setInterval'
onPress={()=>{
this.interval=setInterval(() => {this.setState({sum:(this.state.sum+1)});
},400);
}}
/>
<CustomButton text='clearInterval'
onPress={()=>{
this.interval && clearInterval(this.interval);
}}
/>
setInterval 定时间隔执行