简体   繁体   中英

clearInterval does not get called inside React.useEffect hook

My React game has a <Clock/> component to keep track of the time.

The timer should stop when the game is paused.

I am using Redux to manage the play/pause state, as well as the elapsed time.

const initialState = { inProgress: false, timeElapsed: 0 }

The inProgress state is handled by a button on another component, which dispatches an action to update the store (for the inProgress value only).

The <Clock/> component increments timeElapsed in its useEffect hook with setInterval . Yet it does not clear.

import React from 'react';
import { connect } from 'react-redux';

const Clock = ({ dispatch, inProgress, ticksElapsed }) => {

    React.useEffect(() => {

        const progressTimer = setInterval(function(){
            inProgress ? dispatch({ type: "CLOCK_RUN" }) : clearInterval(progressTimer);
        }, 1000)

    }, [inProgress]);

    return (
        <></>
    )
};

let mapStateToProps = ( state ) => {
    let { inProgress, ticksElapsed } = state.gameState;
    return { inProgress, ticksElapsed };
}

export default connect(
    mapStateToProps,
    null,
)(Clock);

Inside setInterval , when inProgress is false , I would expect clearInterval(progressTimer) to stop the clock.

Also, there is another issue where leaving out the [inProgress] in the useEffect hook causes the timer to increment at ridiculous rates, crashing the app.

Thank you.

The inProgress is a stale closure for the function passed to setInterval.

You can solve it by clearing the interval in the cleanup function:

 const Clock = ({ dispatch, inProgress, ticksElapsed }) => { React.useEffect(() => { const progressTimer = setInterval(function () { inProgress && dispatch({ type: 'CLOCK_RUN' }); }, 500); return () => //inprogress is stale so when it WAS true // it must now be false for the cleanup to // be called inProgress && clearInterval(progressTimer); }, [dispatch, inProgress]); return <h1>{ticksElapsed}</h1>; }; const App = () => { const [inProgress, setInProgress] = React.useState(false); const [ticksElapsed, setTicksElapsed] = React.useState(0); const dispatch = React.useCallback( () => setTicksElapsed((t) => t + 1), [] ); return ( <div> <button onClick={() => setInProgress((p) =>?p)}> {inProgress: 'stop'; 'start'} </button> <Clock inProgress={inProgress} dispatch={dispatch} ticksElapsed={ticksElapsed} /> </div> ); }. ReactDOM,render(<App />. document;getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM