Example of React Native Timer and Stopwatch

React Native Timer and React Native Stopwatch

This is an Example of React Native Timer and React Native Stopwatch. To make a Stopwatch and Timer we have a very good library called react-native-stopwatch-timer. It will provide Stopwatch and Timer component.

A Stopwatch is a special watch that can be used to count the time. In stopwatch time starts from zero and runs until we stop it but Timer is the exact opposite of it. In the Timer, we decide the time to count and it counts towards zero.

Stopwatch

<Stopwatch laps msecs 
  start={this.state.isStopwatchStart}
  // To start
  reset={this.state.resetStopwatch}
  // To reset
  options={options}
  // Options for the styling
  getTime={this.getFormattedTime} 
/>

Timer

<Timer 
  totalDuration={this.state.timerDuration} msecs 
  // Time Duration
  start={this.state.isTimerStart}
  // To start
  reset={this.state.resetTimer}
  // To reset
  options={options}
  // Options for the styling
  handleFinish={handleTimerComplete}
  // Can call a function On finish of the time 
  getTime={this.getFormattedTime} 
/>

In this example, we will make a Stopwatch and a Timer. The Timer will show the count down from the given Millisecond.  So Let’s get started.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To use Stopwatch and Timer you need to install react-native-stopwatch-timer package.

To install this open the terminal and jump into your project using

cd ProjectName

Run the following command

npm install react-native-stopwatch-timer --save

This command will copy all the dependencies into your node_module directory, You can find the directory in node_module directory named react-native-stopwatch-timer.
–save is optional, it is just to update the react-native-app-intro-slider dependency in your package.json file.

Code

Now Open App.js in any code editor and replace the code with the following code

App.js

// Example of React Native Timer and Stopwatch
// https://aboutreact.com/react-native-timer-stopwatch/

// import React in our code
import React, {useState} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
} from 'react-native';

// importing library to use Stopwatch and Timer
import {Stopwatch, Timer} from 'react-native-stopwatch-timer';

const App = () => {
  const [isTimerStart, setIsTimerStart] = useState(false);
  const [isStopwatchStart, setIsStopwatchStart] = useState(false);
  const [timerDuration, setTimerDuration] = useState(90000);
  const [resetTimer, setResetTimer] = useState(false);
  const [resetStopwatch, setResetStopwatch] = useState(false);

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.title}>
          Example of React Native Timer and Stopwatch
        </Text>
        <View style={styles.sectionStyle}>
          <Stopwatch
            laps
            msecs
            start={isStopwatchStart}
            // To start
            reset={resetStopwatch}
            // To reset
            options={options}
            // Options for the styling
            getTime={(time) => {
              console.log(time);
            }}
          />
          <TouchableHighlight
            onPress={() => {
              setIsStopwatchStart(!isStopwatchStart);
              setResetStopwatch(false);
            }}>
            <Text style={styles.buttonText}>
              {!isStopwatchStart ? 'START' : 'STOP'}
            </Text>
          </TouchableHighlight>
          <TouchableHighlight
            onPress={() => {
              setIsStopwatchStart(false);
              setResetStopwatch(true);
            }}>
            <Text style={styles.buttonText}>RESET</Text>
          </TouchableHighlight>
        </View>
        <View style={styles.sectionStyle}>
          <Timer
            totalDuration={timerDuration}
            msecs
            // Time Duration
            start={isTimerStart}
            // To start
            reset={resetTimer}
            // To reset
            options={options}
            // Options for the styling
            handleFinish={() => {
              alert('Custom Completion Function');
            }}
            // Can call a function On finish of the time
            getTime={(time) => {
              console.log(time);
            }}
          />
          <TouchableHighlight
            onPress={() => {
              setIsTimerStart(!isTimerStart);
              setResetTimer(false);
            }}>
            <Text style={styles.buttonText}>
              {!isTimerStart ? 'START' : 'STOP'}
            </Text>
          </TouchableHighlight>
          <TouchableHighlight
            onPress={() => {
              setIsTimerStart(false);
              setResetTimer(true);
            }}>
            <Text style={styles.buttonText}>RESET</Text>
          </TouchableHighlight>
        </View>
      </View>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    textAlign: 'center',
    fontSize: 20,
    fontWeight: 'bold',
    padding: 20,
  },
  sectionStyle: {
    flex: 1,
    marginTop: 32,
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonText: {
    fontSize: 20,
    marginTop: 10,
  },
});

const options = {
  container: {
    backgroundColor: '#FF0000',
    padding: 5,
    borderRadius: 5,
    width: 200,
    alignItems: 'center',
  },
  text: {
    fontSize: 25,
    color: '#FFF',
    marginLeft: 7,
  },
};

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

          

Output in Online Emulator

That was the React Native Timer and React Native Stopwatch. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

13 thoughts on “Example of React Native Timer and Stopwatch”

    • You can see getFormattedTime method which is called when the stopwatch time changes.

      getFormattedTime(time) {
      this.currentTime = time;
      }

      You can make a global variable and define the value into it and whenever you want to know the current time you can access it from that variable.

      Reply
  1. i have create the global variable and define the value into it. but it is not working and you make some code which will help.

    Reply
    • Hi Sheila,
      In the updated version of the library we have a startTime prop where we can define the starting time or the base time from where we want to start like startTime={90000} here 90000 is in milliseconds.

      So what you can do is, keep the current time when user clicked on the start button in AsyncStorage. Now if user exits the page
      You can use focus listener from Navigation to know if user is leaving the current page or came back, You can see this for more help on this.

      const unsubscribe = navigation.addListener('focus', () => {
        // Do whatever you want
      });

      Once you know user came back you can calculate the difference of stored time in AsyncStorage and current time and set it into stopwatch using startTime.

      Reply
  2. Hi, How to get time in milliseconds from the time which we get from this

    getTime={(time) => {
    console.log(time);
    }}

    how can I convert this time to milliseconds in order to use it later,

    Please Help!

    Reply
      • Thanks, One More Problem, when I use startTime with state const,
        Now timer Is not update with state,
        As I setState with 5000 milliseconds, it shows 00:00:00:00 but when I click on reset button then it shows correct start time,

        How to get rid of this?

        Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.