john
john

Reputation: 13

how to countdown timer run in reactnative

I have the following function but its show error after call setTimeout when I comment

// setTimeout(this.clock, 1000);

its working I want countdown timer.

this.state.text = "45:59"

undefined is not an object(evluating this.state.text)

clock() { 
    let presentTime = this.state.text;      

    var timeArray = presentTime.split(/[:]+/);
    var m = timeArray[0];
    var s = this.checkSecond((timeArray[1] - 1));
    if(s==59){m=m-1} 
    this.setState({text:  m + ":" + s}) 
    setTimeout(this.clock, 1000);
}

checkSecond(sec) {
    if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
    if (sec < 0) {sec = "59"};
    return sec;
}

Upvotes: 0

Views: 997

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138235

You need to bind to not loose context:

setTimeout(this.clock.bind(this), 1000);

or

setTimeout(() => this.clock(), 1000);

Upvotes: 1

Related Questions