The setTimeout(function(){}) is used to set a valued interval time to execute a particular task. This function would hold the event to defined time(In milliseconds-seconds) and than execute the Method. So in this tutorial we would going to create a react native app to Call Function Task After Some Time Delay Using setTimeout(function(){}) in android iOS application.
Note: 1000 Milliseconds = 1 second.
Contents in this project Call Function Task After Some Time Delay Using setTimeout(function()) in React Native App:
1. Import StyleSheet, View, Button and Alert component in your project.
1 2 3 |
import React, { Component } from 'react'; import { StyleSheet, View, Button, Alert } from 'react-native'; |
2. Create a function named as ShowAlertWithDelay() in your class. Inside this function scope we would create the setTimeout(function(){}) with Just a Alert message. We would define the time as 5000 milliseconds which represents 5 seconds. So when we call this function on button onPress event it will show the Alert message after 5 seconds of delay.
1 2 3 4 5 6 7 8 9 10 11 |
ShowAlertWithDelay=()=>{ setTimeout(function(){ //Put All Your Code Here, Which You Want To Execute After Some Delay Time. Alert.alert("Alert Shows After 5 Seconds of Delay.") }, 5000); } |
3. Create a Root View in render’s return block and Inside the View we would make a Button component and Call the ShowAlertWithDelay() function on button onPress event.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
render() { return ( <View style={styles.MainContainer}> <Button title="CLICK HERE TO SHOW ALERT WITH 5 SECONDS OF DELAY" onPress={this.ShowAlertWithDelay} /> </View> ); } |
4. Create Style.
1 2 3 4 5 6 7 8 9 10 11 12 |
const styles = StyleSheet.create({ MainContainer :{ flex:1, justifyContent: 'center', alignItems: 'center', margin: 10 } }); |
5. Complete source code for App.js File :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import React, { Component } from 'react'; import { StyleSheet, View, Button, Alert } from 'react-native'; export default class MainActivity extends Component { ShowAlertWithDelay=()=>{ setTimeout(function(){ //Put All Your Code Here, Which You Want To Execute After Some Delay Time. Alert.alert("Alert Shows After 5 Seconds of Delay.") }, 5000); } render() { return ( <View style={styles.MainContainer}> <Button title="CLICK HERE TO SHOW ALERT WITH 5 SECONDS OF DELAY" onPress={this.ShowAlertWithDelay} /> </View> ); } } const styles = StyleSheet.create({ MainContainer :{ flex:1, justifyContent: 'center', alignItems: 'center', margin: 10 } }); |
Screenshot in Android device :

Thanks for the tutorials. Some of them are really useful. Hope you would create more tutorials like these.
Thanks for your comment 🙂