簡體   English   中英

使用useEffect時標簽不活動時如何停止setInterval?

[英]How to stop setInterval when tab is not active while using useEffect?

我在setInterval中使用useEffect 當使用不主動使用標簽時,我不會要求永遠。 它導致一些 memory 問題。 我必須每3000ms獲取一次數據,當用戶不主動使用此選項卡時也要停止它。 我怎么能做這樣的事情?

我嘗試使用document.visibiltyState但無法使用。

我的代碼:

useEffect(() => {
    try {
        const interval = setInterval(() => {
            getTransactionGroupStats()

            getTransactionGroups()

        }, 3000)

        getBinanceBalanceStats()

        return () => {
            clearInterval(interval)
        }
    } catch (error) {
        console.error(error)
    }
}, [])

您可以用戶事件偵聽器並偵聽事件焦點和模糊。 當用戶在該選項卡上時聚焦當用戶離開該選項卡時模糊

useEffect(() => {
     let interval ;
        const unsubscribe = navigation.addListener('focus', () => {
          try {
            interval = setInterval(() => {
                getTransactionGroupStats()
    
                getTransactionGroups()
    
            }, 3000)
    
            getBinanceBalanceStats()
    
           
        } catch (error) {
            console.error(error)
        }
        });
        
        // if user navigate clean interval 
        navigation.addListener('blur', () => {
         clearInterval(interval)
        });
    
        // Return the function to unsubscribe from the event so it gets removed on unmount
        return unsubscribe;
      }, []);

另一種選擇並且更具可擴展性可能是您創建一個自定義掛鈎以查看用戶是否處於活動狀態,並且每次更改時您都執行 useEffect

useActive.ts

export const useActive = (time: number) => {
    const [active, setActive] = useState(false)
    const timer: any = useRef()
    const events = ['keypress', 'mousemove', 'touchmove', 'click', 'scroll']

    useEffect(() => {
        const handleEvent = () => {
            setActive(true)
            if (timer.current) {
                window.clearTimeout(timer.current)
            }
            timer.current = window.setTimeout(() => {
                setActive(false)
            }, time)
        }

        events.forEach((event: string) => document.addEventListener(event, handleEvent))

        return () => {
            events.forEach((event: string) => document.removeEventListener(event, handleEvent))
        }
    }, [time])

    return active
}

YourApp.tsx

const active = useActive(3000)

useEffect(() => {
   if(active){
     try {
            const interval = setInterval(() => {
            getTransactionGroupStats()

            getTransactionGroups()

        }, 3000)

        getBinanceBalanceStats()

        return () => {
            clearInterval(interval)
        }
    } catch (error) {
        console.error(error)
    }

  }
}, [active])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM