简体   繁体   English

clearinterval 在反应 typescript 中不起作用

[英]clearinterval is not working in react typescript

i am struggling in clearInterval function for typescript in react, don't know why it is not clearing interval, for that i have defined variable let interval_counter;我在clearInterval function for typescript 中挣扎,不知道为什么它没有清除间隔,因为我定义了变量let interval_counter; and this variable i using as this interval_counter = setInterval(interval,1000);我使用这个变量作为这个interval_counter = setInterval(interval,1000); , but when i used clearInterval(interval_counter); ,但是当我使用clearInterval(interval_counter); , it is not working for me, here i have put my whole code, can anyone please look my code and help me to resolve this issue? ,它不适合我,我已经把我的整个代码放在这里了,任何人都可以看看我的代码并帮助我解决这个问题吗? any help will be really appreciated.任何帮助将不胜感激。

interface Props {
    gameId: string;
}

let interval_counter;

export const GameInner: React.FC<Props> = (
    {
        gameId,
    }


) => {
    
    const gameData = useDataStore(GameDataStore);
    const userData = useDataStore(UserDataStore);
    const chatData = useDataStore(ChatDataStore);
    const params = useParams<{ throwaway?: string }>();
    const history = useHistory();
    const [updateShowTimer, setUpdateShowTimer] = React.useState('02:00');
    const [isCalled, setIsCalled] = React.useState<any>('0');
    let setSeconds = 30;
    //const interval_counter =  React.useRef<any>();
    //React.createRef<any>();

    

    const {
        dateCreated,
        started,
        chooserGuid,
        ownerGuid,
        spectators,
        pendingPlayers,
        players,
        settings,
        kickedPlayers
    } = gameData.game ?? {};

    const {
        playerGuid
    } = userData;

    const iWasKicked = !!kickedPlayers?.[playerGuid];
    const amInGame = playerGuid in (players ?? {});


    const skipPlayer = (game_string_id: any, target_turn: any, chooserGuid: any) => {
        return GameDataStore.skipPlayer(game_string_id, target_turn, chooserGuid);
    }

    const interval = () => {
        let timer = setSeconds, minutes, seconds;

        let chooserGuid = localStorage.getItem('chooserGuid');
        let game_string_id = localStorage.getItem('game_id');
        let target_turn = localStorage.getItem('target_turn');
        let is_called = localStorage.getItem('is_called');

        if (typeof timer !== undefined && timer != null) {
            minutes = parseInt(timer / 60 as any, 10);
            seconds = parseInt(timer % 60 as any, 10);
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            //console.log("test");
            console.log(minutes + ":" + seconds);

            setUpdateShowTimer(minutes+":"+seconds);

            if (timer == 0) {
                if(gameData?.game?.roundStarted) {
                    
                } else {
                    skipPlayer(game_string_id, target_turn, chooserGuid);
                }
                clearInterval(interval_counter);
            }

            if (--timer < 0) {
                clearInterval(interval_counter);
            }
            setSeconds -= 1;
        }

    }

    

    const startTimer = () => {
        console.log("called again");
        interval_counter = setInterval(interval,1000);
    }

    const isOwner = ownerGuid === userData.playerGuid;
    const isChooser = playerGuid === chooserGuid;
    const amSpectating = playerGuid in { ...(spectators ?? {}), ...(pendingPlayers ?? {}) };

    const playerGuids = Object.keys(players ?? {});
    const roundsToWin = getTrueRoundsToWin(gameData.game as ClientGameItem);
    const winnerGuid = playerGuids.find(pg => (players?.[pg].wins ?? 0) >= roundsToWin);

    const inviteLink = (settings?.inviteLink?.length ?? 0) > 25
        ? `${settings?.inviteLink?.substr(0, 25)}...`
        : settings?.inviteLink;

    const meKicked = kickedPlayers?.[playerGuid];

    const tablet = useMediaQuery('(max-width:1200px)');
    const canChat = (amInGame || amSpectating) && moment(dateCreated).isAfter(moment(new Date(1589260798170)));
    const chatBarExpanded = chatData.sidebarOpen && !tablet && canChat;


    /**********************************************/
    if(gameData?.game?.players && gameData?.game?.id) {
        let game_id = gameData.game.id;
        let all_players = gameData.game.players;
        let all_player_id = Object.keys(all_players);
        let filteredAry = all_player_id.filter(e => e !== userData.playerGuid);

        console.log("user player guid:"+userData.playerGuid);
        console.log("guid:"+chooserGuid);   
        console.log("all players:"+all_player_id);  
        console.log("new array:"+filteredAry);

        let target_item = filteredAry.find((_, i, ar) => Math.random() < 1 / (ar.length - i));
        if(typeof target_item !== undefined && target_item!=null) {
            localStorage.setItem('target_turn',target_item);
        }

        localStorage.setItem('is_started','0');
        if(typeof game_id !== undefined && game_id!=null) {
            localStorage.setItem('game_id',game_id);
        }
        if(typeof chooserGuid !== undefined && chooserGuid!=null) {
            localStorage.setItem('chooserGuid',chooserGuid);
        }
        if(isChooser) {
            if(isCalled == '0') {
                setIsCalled("1");
                startTimer();
            }
        } else {
            clearInterval(interval_counter);
        }
        if(gameData?.game?.roundStarted) {
            console.log("round is started");
            clearInterval(interval_counter);
        }
    }
    /********************************************/

    

    return (
        <div style={{ maxWidth: chatBarExpanded ? "calc(100% - 320px)" : "100%" }}>
            
        </div>
    );
};

I believe your problem will be solved when you store your interval also in state.我相信当您将间隔也存储在 state 中时,您的问题将得到解决。

  const [interval, setInterval] = useState(null as NodeJS.Timeout | null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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