react 中使用定时器 Timers(定时器)


  • 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   定时间隔执行
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM