0

Below is my own the Timer Component: (React-Native)

element - contains information about creation date

The timer when loaded at the beginning counts down from 300s to 0 and shows Expired

function Timer({ element }) {
    // I determine the element's validity for 5 minutes (300000 ms)
    const endTime = Number(element.item.created_at) + 300000

    // Field containing the value displayed in the component + initialValue
    const [textTimer, setTextTimer] = useState(() => {
        const diff = endTime - Date.now()
        if (diff <= 0) {
            return 'Expired'
        }
        else {
            return (diff / 1000).toFixed(0)
        }
    })

    // Code that is executed every 1s
    useEffect(() => {
        const diff = endTime - Date.now()
        let interval = null
        if (diff > 0) {
            interval = setInterval(() => {
                setTextTimer(prev => prev - 1)
            }, 1000);
        }
        else {
            setTextTimer('Expired')
        }

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

    return (
        <View>
            <Text>{textTimer}</Text>
        </View>
    )
};

But something is wrong with it.

Refreshing does not occur after 1 second (it is variable)

How do you get a display equal to the specified time? Make this Timer work like real time

DeveloperApps
  • 763
  • 7
  • 16
  • Forgot to do setState? –  Jun 03 '20 at 13:22
  • and try 500ms instead of a second. setTimeout and setInterval are not very precise – mplungjan Jun 03 '20 at 13:24
  • @mplungjan I need the best accuracy possible. Time matters. I tried another solution. I set the interval time to the minimum value and recalculated the time difference again with each call. But this also does not work precisely – DeveloperApps Jun 03 '20 at 13:34

0 Answers0