B
B
boban222021-04-08 14:09:56
JavaScript
boban22, 2021-04-08 14:09:56

How to fix the error with the timer?

I made a timer to call a request every 10 seconds, the timer works, but an error occurs TypeError: setInterval(...) is not a function, how to fix it so that the timer works the same way?

useEffect(()=> {
        (
            setInterval(async()=>{
                const response = await fetch('http://127.0.0.1:8000/api/timecalculate', {
                method: 'PUT',
                headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'},
                credentials: 'include',
            });
            var now = new Date();
            const content = await response.json();
            console.log(content + now);
            },10000)
        )()
        }
    )

unknown.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-04-08
@boban22

useEffect(() => {
    let intervalId = setInterval(async () => {
        const response = await fetch('http://127.0.0.1:8000/api/timecalculate', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
            credentials: 'include',
        });
        const content = await response.json();
        const now = new Date();

        console.log(content + now);
    }, 10000)

    return () => {
        clearInterval(intervalId);
    };
}, []);

UPD : https://codesandbox.io/s/qna-q969499-m7b1n

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question