setInterval() does not work

Asked

Viewed 79 times

0

I am creating a question application, where it displays a timer, if the timer reaches 0, the question will be lost (ie if the user does not answer in time), but when displaying the number is oscillating, it tries to decrease but then goes back to "80" or to "50", is all the time between 79.9 - 80 - 79.9 - 80, I do not know why this happens, I suspect it is something related when I pass the parameter "item.time" to the function, anyone knows how to solve? pff ;-;

the logic of the code is similar to this:

      let questions = [
        { title: "quanto é 1 + 1?", time: 50 },
        { title: "quanto é 2 + 2?", time: 80 }
    ]
    const [timeQ, setTimeQ] = useState(0)
    let interval;

    function QuestionTimer(tempo) {

        interval = setInterval(()=>{
            setTimeQ(( tempo -= 0.1).toFixed(2))
            console.log(timeQ)

        },100)
        if( tempo <=0){
            errou()
            clearInterval(interval)
        }

    }

    function render() {
        return (
            <div id="timer">
                {questions.map((item, indice) => {
                        if (item.time !== undefined) {

                            return QuestionTimer(item.time)


                        }

                })}
            </div>
        )
    }

1 answer

0

Try declaring the time variable as well.

let interval, tempo; 

when calling the function save time to go decreasing

function QuestionTimer(tempTempo) {
        tempo = tempTempo;
  • didn’t work buddy :(, continues oscillating "80-79-80-79"

  • It is that information is missing to be able to analyze the whole. What makes the setTimeQ function?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.