React: Timer with setInterval in components

Veröffentlicht von

Start and stop timers in React components.

I had a need in a project for a timer which updates something periodically. In doing so, I had a small problem, my example application:

I naively started the timer simply in the component:

However, React is quite smart and loads and updates the components in the background, which meant that this code was executed over and over again when switching between tabs. As a result, new timer events were registered over and over again.

My solution was to convert the component into a React component. This then brings things like “componentDidMount()” and “componentWillUnmount()”. These events are executed when the component is displayed and also when it disappears.

import * as React from 'react';
 
class Clock extends React.Component<any, any> {
    private timerId: any;
 
    constructor(props: any) {
        super(props);
        this.state = {  currentTime : "-" };
    }
 
    componentDidMount() {
        console.log("Starting timer 1");
        this.timerId = setInterval(this.updateStatus, 1000);
    }
 
    componentWillUnmount() {
        console.log("Stopping timer 2");
        clearInterval(this.timerId);
    }
 
    updateStatus = () => {
        console.log("Timer 1 fired");
        let currentdate = new Date();
        let datetime = "Last Sync: " + currentdate.getDate() + "/"
            + (currentdate.getMonth()+1)  + "/"
            + currentdate.getFullYear() + " @ "
            + currentdate.getHours() + ":"
            + currentdate.getMinutes() + ":"
            + currentdate.getSeconds();
 
        this.setState({ currentTime: datetime});
    }
 
    render() {
        return <div>
            <p>{this.state.currentTime}</p>
        </div>
    };
}
 
export default Clock;

This allows to store the reference to the timer, the ID, and to remove the timer when hiding it with “clearInterval”.

Done! The timer is now started and stopped again, so that it is only active once.

The sample code of the project is available on Github.

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert