How to Use Set Timeout in React Native

Last Updated on December 10, 2020.

Sometimes, we may need to execute code after some delay. In such cases, we use JavaScript method setTimeout in React Native. SetTimeout method is used to execute a function after waiting a specific amount of time.

See the following snippet to see how do we use setTimeout method. The yourFunction will execute only after 3000 milliseconds, that is 3 seconds.

setTimeout(() => {
yourFunction();
}, 3000);

In the following react native setTimeout example, the method is used inside componentDidMount lifecycle. When the time period of 5 seconds finishes the alert will appear on the screen. The timeout method can be used in class-based components as given below.

import React, {Component} from 'react';
import {View, Text, Alert} from 'react-native';

class App extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    setTimeout(() => {
      Alert.alert('I am appearing...', 'After 5 seconds!');
    }, 5000);
  }

  render() {
    return (
      <View style={{justifyContent: 'center', alignItems: 'center'}}>
        <Text style={{color: 'black'}}>Alert will appear after 5 seconds</Text>
      </View>
    );
  }
}

export default App;

The timeout method can be used in function based components as given below.

import React, {useEffect} from 'react';
import {View, Text, Alert} from 'react-native';

const App = () => {
  useEffect(() => {
    setTimeout(() => {
      Alert.alert('I am appearing...', 'After 5 seconds!');
    }, 5000);
  }, []);
  return (
    <View style={{justifyContent: 'center', alignItems: 'center'}}>
      <Text style={{color: 'black'}}>Alert will appear after 5 seconds</Text>
    </View>
  );
};

export default App;

This is how you use the setTimeout method in React Native. The output is as given below. If you have any doubts then don’t hesitate to use the comment section.

1 thought on “How to Use Set Timeout in React Native”

  1. Pingback: How to Make React Native Modal Close Automatically - REACT NATIVE FOR YOU

Leave a Reply

%d bloggers like this: