React 中的 setTimeout 和clearTimeout

2024-03-26

当用户使用 setTimeout 和clearTimeout 在页面上 30 秒内没有进行任何点击事件时,我正在努力创建注销功能。

但每次用户点击页面上的任何内容时,剩余时间必须再次重置为 30 秒(或者作为另一个选项,将使用clearTimeOut 和 setTimeOut。)同时,当用户没有点击页面上的任何内容时,他们通过删除 accessToken,将在 30 秒后自动注销。

所以为了解决这个问题,我的方法是这样的:

  • 当用户访问此页面时,setTimeout() 将开始。

  • 当用户单击页面上的某些内容时,clearTimeOut 将被激活,setTimeOut 也将再次被激活

  • 当用户30秒内没有点击页面上的任何内容时,他们将通过删除本地存储中的accessToken自动注销

目前,通过删除访问令牌可以让用户在 30 秒后注销! UseEffect 中的 setTimeOut 也有效。

唯一的问题是我不知道当用户在页面上单击事件时如何使clearTimeOut()和setTimeOut工作。

import styled from 'styled-components';
import React, {useRef, useEffect, useState} from 'react';
import ScreenContainer from '../../src/component/common/ScreenContainer';
import {useNavigate as useDomNavigate} from 'react-router-dom';
import isNil from 'lodash/isNil';
import userClient from '../../src/client/user/userClient';

const Device = () => {
    const domNavigate = useDomNavigate();
    const [storeId, setStoreId] = useState(() => JSON.parse(localStorage.getItem('storeId')));
    const [currentDeposit, setCurrentDeposit] = useState<number>(0);
    const depositBalanceInfo = userClient.getDepositBalanceByStoreId(storeId, isNil(storeId)).data;

    const [time, setTime] = useState(1500);

    const logout = () => {
        localStorage.removeItem('accessToken');
        domNavigate(`/home/home`);
    };

    //////////////////////////
    // below is the code that I wrote to make it work..
 

    const myFunc = () => {
        // remove accessToken for logout
        localStorage.removeItem('accessToken');

        // move to home page
        domNavigate(`/home/home`);
    }

    // begin setTimeOut automatically when the users come over to this page from another one.
    useEffect(() => {
        const timeoutBegins = window.setTimeout(myFunc, 3000);
        return () => clearTimeout(timeoutBegins); 
    }, [])

    // when the users click anything on the page, it clears current setTimeOut function and restart the setTimeOut function again.
    const clickDisplay = () => {
        clearTimeout(timeoutBegins);
        timeOutBegins();
    }



   ///////////////////////////////////////// 

    useEffect(() => {
        if (storeId && depositBalanceInfo) {
            setCurrentDeposit(depositBalanceInfo?.depositBalance);
        }
    }, [storeId, depositBalanceInfo?.depositBalance]);

    return (
        <ScreenContainer>
            <Wrapper>
                <div>Choose Payment Option</div>
                <button onClick={() => window.history.back()}>go back</button>
                <div>Your Balance: {currentDeposit.toLocaleString()}dollar</div>
                <br />
                <button onClick={() => domNavigate(`/charge/step2-select-price/?chargeMethod=card`)}>Credit Card Payment</button>
                <br />
                <button onClick={() => domNavigate(`/charge/step2-select-price/?chargeMethod=cash`)}>Cash Payment</button>
                <br />
                <button onClick={() => domNavigate(`/home/checkUserByPin`)}>Reset Password</button>
                <br />
                <button onClick={logout}>Logout</button>
            </Wrapper>
        </ScreenContainer>
    );
};

const Wrapper = styled.div`
    border: 1px solid red;
`;

export default Device;

你可以做这样的事情。因此,您运行计时器,每次单击文档中的某个位置时,它都会取消当前计时器并运行新计时器。所以你的myFunc仅当用户在 N 秒后未单击页面时,该函数才会运行。

请记住,您想在 30 秒内完成,您需要投入 30000setTimeout

const timerId = useRef(null)

  const myFunc = () => {
    clearTimeout(timerId.current)
    timerId.current = null
    console.log('DO SOMETHING')
  }

  const onDocumentClick = () => {
    if (timerId.current) {
      clearTimeout(timerId.current)
      timerId.current = window.setTimeout(myFunc, 3000)
    }
  }

  useEffect(() => {
    timerId.current = window.setTimeout(myFunc, 3000)

    document.addEventListener('click', onDocumentClick)
    return () => {
      clearTimeout(timerId.current)
      document.removeEventListener('click', onDocumentClick)
    }
  }, [])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 中的 setTimeout 和clearTimeout 的相关文章

随机推荐