一、簡介
定時器在需求中也是一個常見的部分,例如在間隔時間內循環執行某些業務或者定時推送消息等。ReactNative中提供了三種定時器API,分別是setTimeout、setInterval、setImmediate。它們都是遵循瀏覽器API標准實現的,但是作用也略有不同。
二、API
1、setTimeout:主要用於設定一個定時任務,只會執行一次。在達到某個時間點時開始執行此任務, 例如打開APP 5秒后開始獲取用戶的位置信息。
//定時器對應的ID declare opaque type TimeoutID; //根據ID清除對應的定時器 declare function clearTimeout(timeoutId?: TimeoutID): void; //設定定時器,返回對應的ID //callback是定時器內的執行函數 //ms是時間片,毫秒 declare function setTimeout<TArguments: Array<mixed>>( callback: (...args: TArguments) => mixed, ms?: number, ...args: TArguments ): TimeoutID
2、setInterval:主要用於設定循環執行的任務。以某個時間段為間隔,不停地執行此任務,例如,輪播圖。
//定時器對應的ID declare opaque type IntervalID; //根據ID清除對應的定時器 declare function clearInterval(intervalId?: IntervalID): void; //設定定時器,返回對應的ID //callback是定時器內的執行函數 //ms是時間片,毫秒 declare function setInterval<TArguments: Array<mixed>>( callback: (...args: TArguments) => mixed, ms?: number, ...args: TArguments ): IntervalID
3、setImmediate:主要用於設定立即執行的任務,只會執行一次。函數一旦調用,立馬執行此任務,例如程序一啟動,就開始推送消息給用戶。
//設定定時器對象,只有一個參數callback為執行體函數 declare function setImmediate(callback: ((...args: Array<any>) => mixed), ...args: Array<any>): Object; //移除定時器對象 declare function clearImmediate(immediateObject: any): Object;
三、使用
簡單示例如下:
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, TouchableHighlight, View } from 'react-native'; export default class App extends Component { constructor(){ super(); this.state = {count:0}; } //事件 _event1(){ //1秒后執行callback, 只會執行一次 const timeoutID = setTimeout(()=>{ //執行 alert("1秒時間到了,開始執行"); //清除 clearTimeout(timeoutID); }, 1000) } _event2(){ //每間隔1秒執行callback,會不停地執行 const intervalID = setInterval(() => { //累計 this.setState({ count: this.state.count+1}); //移除 if (this.state.count === 3){ alert("count==3,移除定時器"); clearInterval(intervalID); this.setState({ count: 0}); } }, 1000) } _event3(){ //立即執行, 只執行一次 const object = setImmediate(()=>{ //執行 alert("立即執行"); //移除 clearImmediate(object); }); } render() { return ( <View style={styles.container}> <TouchableHighlight onPress={this._event1.bind(this)}> <Text style={{color:'red', fontSize:25}}>setTimeout</Text> </TouchableHighlight> <TouchableHighlight onPress={this._event2.bind(this)}> <Text style={{color:'red', marginTop:30, fontSize:25}}>setInterval{":"+this.state.count}</Text> </TouchableHighlight> <TouchableHighlight onPress={this._event3.bind(this)}> <Text style={{color:'red', marginTop:30, fontSize:25}}>setImmediate</Text> </TouchableHighlight> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', } }); AppRegistry.registerComponent('App', () => App);