Search code examples
reactjsglobal-variablescountdownclearinterval

making a global variable in React to use clearInterval


I am learning React and I stumble upon a problem I could not find an answer for a few days already. I am trying to make an app similar to countdown app. in this app, I can make countdown runs but I cannot get access to timer function to use clearInterval since timer is restricted in its function scope. is there anyway I can use clearInterval ontimer so I can pause begin function? In javascript vanilla, I can declare timer as a global variable and get access to it anywhere, but in react I do not know how to do it. I will be much appreciate for your help

import React from 'react';
import ReactDOM from 'react-dom';

class Countdown extends React.Component{
    constructor(){
        super();
        this.state ={count:10};
    }

    render(){
        return(
            <div>
                <button onClick={()=>begin(this.state.count)}>start</button>
                <button>pause</button>
                <button>continue</button>
            </div>
        );
    }
};

const begin=(c)=>{
    let count = c;
    const timer = setInterval(countdown,1000);
    function countdown(){
        count=count-1
        if (count<0){
            clearInterval(timer);
            return; 
        }

        console.log(count)
    }
}

ReactDOM.render(<Countdown/>, document.getElementById('app'));

Solution

  • You would rather define the begin function in the component class itself and declare the timer as a class property like

    class Countdown extends React.Component{
        constructor(){
            super();
            this.state ={count:10};
            this.timer = null;
        }
    
        countdown = (count) => {
            count= count-1
            if (count<0){
                clearInterval(this.timer);
                return; 
            }
    
        }
        begin=() => {
          const count = this.state.count
          this.timer = setInterval(() => countdown(count),1000);
    
        }
        render(){
            return(
                <div>
                    <button onClick={this.begin}>start</button>
                    <button>pause</button>
                    <button>continue</button>
                </div>
            );
        }
    };