AppNovice
AppNovice

Reputation: 21

Why is setInterval being called automatically in react native

I am trying to make a simple clock that starts and stops on the press of a button. Here I have set a variable equal to a setInterval so that I can clear it later on. But for some reason, it is being called without the button being pressed.

Here the autoInc should have been called ideally when I pressed the "Start" button but it gets called anyway.

import React, { Component } from "react";
import { Text, View, Button } from "react-native";

export default class Counter extends Component {
  increaser = () => {
    this.setState(prePre => {
      return { counter: prePre.counter + 1 };
    });
  };

  constructor(props) {
    super(props);

    this.state = {
      counter: 0,
      wantToShow: true
    };
    autoInc = setInterval(this.increaser, 1000);
  }

  render() {
    if (this.state.wantToShow)
      return (
        <View>
          <Text style={{ color: "red", fontSize: 50, textAlign: "center" }}>
            {this.state.counter}
          </Text>
          <Button title="Start" onPress={this.autoInc} />
        </View>
      );
  }
}

Upvotes: 1

Views: 1104

Answers (2)

oma
oma

Reputation: 1894

A full react example here, you just have to translate functions in react native.

Create a variable this.interval=null in your constructor, assign to this the interval in the startFn , then just remove it with window.clearInterval(this.interval);

export default class App extends Component {
  constructor(props) {
    super(props);
    this.interval = null;
  }

  componentDidMount() {}

  startFn = () => {
    console.log("assign and start the interval");
    this.interval = setInterval(this.callbackFn, 1000);
  };

  stopFn = () => {
    console.log("clear interval");
    window.clearInterval(this.interval);
  };

  callbackFn = () => {
    console.log("interval callback function");
  };

  render(props, { results = [] }) {
    return (
      <div>
        <h1>Example</h1>
        <button onClick={this.startFn}>start Interval</button>
        <button onClick={this.stopFn}>stop Interval</button>
      </div>
    );
  }
}

Codesandbox example here: https://codesandbox.io/s/j737qj23r5

Upvotes: 3

Lennholm
Lennholm

Reputation: 7470

In your constructor, you call setInterval(this.increaser,1000) and then assign its return value to the global property autoInc.
this.autoInc is undefined in your render function.

It looks like

autoInc = setInterval(this.increaser,1000)

is simply incorrectly written and what you want instead is:

this.autoInc = () => setInterval(this.increaser,1000)

Upvotes: 1

Related Questions