Why is setInterval being called automatically in react native

1842 views javascript
3

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>
            )

}

}

answered question

Because your constructor calls setInterval

@tkausl does my constructor call all the setIntervals, even those are not in the constructor scope?

2 Answers

11

here is your issue: onPress={this.autoInc}

This will call your function, you have to onPress={() => {this.autoInc()}} set the callback, which will call the interval function.

And you assign your variable the setIntervaldirectly. Use this:

 autoInc = () => {
    setInterval(this.fn, 1000)
};

posted this
11

place this code of out constructor

 autoInc = () => {
        setInterval(this.fn, 1000)
    };

posted this

Have an answer?

JD

Please login first before posting an answer.