How to setup React-Native Background Timer

Asbar Ali

Hey guy! What’s going on today! In this article, We are going to set up the background timer.

These are the steps that I'm going to achieve the final result!

  1. Initialize new React Native Project
  2. Implement the Timer using Javascript SetInterval
  3. Install Background Timer
  4. Use Background Timer Interval and Clear Interval

(Note: Check the full code at the end of this article)

01. Initialize new React Native Project

Well! First thing we want to do is creating a new project. Simply we can use react-native-init command for it and I use project name as backgroundTimer

react-native init backgroundTimer

Now project will be created with the latest react native version.

02. Implement the Timer using Javascript SetInterval

In here, now we’re going to create a simple timer and that it is counting up. we can have count down too. But we go with count up.

Now create 2 files for timer component and style for it. Let’s name timer component as timerComponet.

In the timer component,

Create 3 render methods for the start, pause and reset buttons. Inside the render start button method, implement react native button and mainly use 2 props here. (title and onPress)

Timer.component.jsrenderStartButton = () => {
return (
<Button
title="Start"
onPress={this.onStart}
/>
)
}
renderPauseButton = () => {
return (
<Button
title="Pause"
onPress={this.onPause}
/>
)
}
renderResetButton = () => {
return (
<Button
title="Reset"
onPress={this.onReset}
/>
)
}

Let put these 3 buttons in a wrapper view because we want to align those 3 buttons in the same row.

Timer.component.jsrender() {
<View style={styles.container}>
<View style={styles.buttonWrapper}>
{this.renderStartButton()}
{this.renderPauseButton()}
{this.renderResetButton()}

</View>
</View>
}

Go to the stylesheet we created for timer component. For the button Wrapper, Add width to 100% and Specify the direction with flexDirection because we want to keep it as a row.

If put space-around for justify-content, Items are positions with space before, between and after the current line.

Timer.styles.jsbuttonWrapper: {
width: '100%',
flexDirection: 'row',
justifyContent: 'space-around',
},

Now add another text to display the timer running in seconds. (Still, we didn’t initialize the second state)

Container style will be the outer wrapper of the timer component and we’ll make a center for both align-items and justify-content.

Timer.component.jsrender() {
<View style={styles.container}>
<Text style={styles.secondText}>{this.state.second}</Text
<View style={styles.buttonWrapper}>
{this.renderStartButton()}
{this.renderPauseButton()}
{this.renderResetButton()}
</View>
</View>
}

Container style -

container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},

Add a style for secondText as well. If increase the font size and text will be visible more clearly.

Timer.styles.jssecondText: {
fontSize: 25,
}

Its time to initialize the variable called second inside the state object. Initially, it should be zero.

Timer.component.jsthis.state = {
second: 0,
}

If we run the application and it should like this,

Now, Let start with onStart callback events. We need to define javascript setInterval to update the second state at every 1 second.

Create a variable to catch the return of setInterval which is used as the parameter for the clearInterval. Now update state second for every second.

Timer.component.js_interval: any;onStart = () => {
this._interval = setInterval(() => {
this.setState({
second: this.state.second + 1,
})
}, 1000);
}

Clear the interval in pause button using Javascript ClearInterval Method. So updating the state variable will be stopped.

Timer.component.jsonPause = () => {
clearInterval(this._interval);
}

OnReset callback event, Clear the interval and set the second state variable to zero as well.

Timer.component.jsonReset = () => {
this.setState({
second: 0,
});
clearInterval(this._interval);
}

Now foreground timer should work.

03. Install Background Timer

yarn add react-native-background-timer

The library is added successfully and use react-native link to link all the dependencies.

react-native link react-native-background-timer

If you use pod in my project and then go to the iOS directory and run the following command.

pod install

If you don’t use pod in the project and I’ll show you how to do it in manual.

First, open the workspace of project in xCode. Then after going to the libraries and right-click it.

Click add files “project name”. In my case, its background timer.

Now go to the node_modules directory in your project. Search the react native background timer library. Inside there, go to the iOS directory and Simply add the .xcodeProj file.

If you already installed it with pods then no need to do the above steps.

04. Use Background Timer Interval and Clear Interval

As a first step, import the react-native background timer library.

Timer.component.jsimport BackgroundTimer from "react-native-background-timer";

For iOS,

We need to start the background timer and it is needed only for the ios. so put a condition to execute using the react native platform. Then use the background timer set interval.

Timer.component.jsonStart = () => {if (Platform.OS =="ios") {
BackgroundTimer.start();
}
this._interval = BackgroundTimer.setInterval(() => {
this.setState({
second: this.state.second + 1,
})
}, 1000);
}

For the clear interval also we should do the same thing.

onPause = () => {
BackgroundTimer.clearInterval(this._interval);
}
onReset = () => {
this.setState({
second: 0,
});
BackgroundTimer.clearInterval(this._interval);
}

Full Code

Timer.component.js// @flowimport React from 'react';
import {View, Text, Button, Platform} from 'react-native';
import PropTypes from 'prop-types';
import type {Element as ReactElement} from 'react';
import BackgroundTimer from "react-native-background-timer";import styles from './Timer.styles';type TimerProps = {};
type TimerState = {};
class TimerComponent extends React.PureComponent<TimerProps, TimerState> {
static defaultProps: any
constructor(props: TimerProps) {
super(props);
this.state = {
second: 0,
}
}
_interval: any;onStart = () => {
if (Platform.OS =="ios") {
BackgroundTimer.start();
}

this._interval = BackgroundTimer.setInterval(() => {
this.setState({
second: this.state.second + 1,
})
}, 1000);
}
onPause = () => {
BackgroundTimer.clearInterval(this._interval);
}
onReset = () => {
this.setState({
second: 0,
});
BackgroundTimer.clearInterval(this._interval);
}
renderStartButton = () => {
return (
<Button
title="Start"
onPress={this.onStart}
/>
)
}
renderPauseButton = () => {
return (
<Button
title="Pause"
onPress={this.onPause}
/>
)
}
renderResetButton = () => {
return (
<Button
title="Reset"
onPress={this.onReset}
/>
)
}
renderContent = (): ReactElement<any> => {
return (
<View style={styles.container}>
<Text style={styles.secondText}>{this.state.second}</Text>
<View style={styles.buttonWrapper}>
{this.renderStartButton()}
{this.renderPauseButton()}
{this.renderResetButton()}
</View>
</View>
);
}
render() {
const content = this.renderContent();
return content;
}
}
TimerComponent.propTypes = {};
TimerComponent.defaultProps = {};
export default TimerComponent;Timer.styles.js - Full Code// @flowimport {StyleSheet} from 'react-native';const style = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
buttonWrapper: {
width: '100%',
flexDirection: 'row',
justifyContent: 'space-around',
},
secondText: {
fontSize: 25,
}
});
export default style;

Source Code: https://github.com/AsbarAli/background-timer

Call the timer component in your base app js file and check the timer running in the background.

It should work :)

Have a nice day!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade