Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

296
Visualizações
react native setInterval fires too fast (using expo)

I made a timer hook for react native which counts from from props to to props. It returns the current value of timer in seconds, start function, stop function, restart function and pause function in an object. Here is the timer code:

import { useState, useEffect, useRef } from 'react'

export default function useTimer({ from, to, intervalS, finished }) {
    const [timer, setTimer] = useState(from)
    const interval = useRef()

    const start = () => {
        if (!interval.current) {
            interval.current = setInterval(() => {
                setTimer(timer => timer - intervalS)
            }, intervalS * 1000)
        }
    }

    const pause = () => {
        clearInterval(interval.current)
        interval.current = null
    }

    const stop = () => {
        clearInterval(interval.current)
        interval.current = null
        setTimer(from)
    }

    const restart = () => {
        clearInterval(interval.current)
        interval.current = null
        setTimer(from)
        start()
    }

    useEffect(() => {
        return () => {
            clearInterval(interval.current)
        }
    }, [])

    useEffect(() => {
        if (timer === to) {
            finished()
            clearInterval(interval.current)
        }
    }, [timer])

    return {
        value: timer,
        start,
        pause,
        restart,
        stop
    }
}

Everything works perfectly but when i try to render (or even console.log) the timer value, it counts faster than what should be. For example the timer will pass 20 seconds for every 15 seconds in real time. I am using Expo Go app for development and my device is an android phone. Am i doing something wrong? Here is how i use timer:

export default function Countdown() {
    const [finished, setFinished] = useState(false)
    const timer = useTimer({ from: 60, to: 0, intervalS: 1, finished: () => setFinished(true) })

    return (
            <View style={{ alignItems: 'center' }}>
                <Typography variant="heading">{timer.value}</Typography>
                <Button title="start" onPress={timer.start} />
                <Button title="pause" onPress={timer.pause} />
                <Button title="restart" onPress={timer.restart} />
                <Button title="stop" onPress={timer.stop} />
            </View>
    )
}

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

For anyone who might be wondering what's wrong, the problem is with expo's development mode. I don't know why but it seems timing is faster in expo's development mode. Just toggle the development mode to production mode and time will become normal

about 4 years ago · Juan Pablo Isaza Relatório

0

I used this approach to create a timer before:

const [intervalID, setIntervalID] = useState<any>(null)
//Initially set to 60 secs
const [testTime, setTestTime] = React.useState(60)

useEffect(() => {
    setIntervalID(setInterval(() => {
        updateTimer();
    }, 1000));

    return () => clearInterval(intervalID);
}, [])

useEffect(() => {
    if (testTime <= 0) {
        //Timer hit zero

        return () => clearInterval(intervalID)
    }
}, [testTime])

const updateTimer = () => {
    setTestTime(testTime => testTime - 1)
}

function displayTime(seconds) {
    const format = val => `0${Math.floor(val)}`.slice(-2)
    const minutes = (seconds % 3600) / 60

    return [minutes, seconds % 60].map(format).join(':')
}

const getRemainingTime = () => {
    let finalTime = displayTime(testTime)
    return <Text style={{ alignSelf: 'center' }}>{finalTime} minutes left</Text>
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda