React Error on 25+5 clock

Tell us what’s happening:
Describe your issue in detail here.

So I am currently doing the final project in the Front End Development Libraries

However I am experiencing a React error on the timeout variable in the clock function error message is displaying
"Expected an assignment or function call and instead saw an expression "

Here is the snippet of the code I am working on.
Your code so far


let timeout = setTimeout(() => {
        if (playTimer && timeNow) {
            setTimeNow(timeNow - 1);
        }
}, 1000);

const startTimer = () => {
        clearTimeout(timeout);
        setPlayTimer(prev => !prev)
}

const clock = () => {
        if (playTimer){
            timeout; // error is pointing here
            resetTimer();
        } else{
            clearTimeout(timeout);
        }
}

useEffect(() => {
        clock()
}, [playTimer, timeout, timeNow]);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0

The error is only showing itself when I do npm start in VScode but it works fine on codepen as seen here **It even passes the whole test on codepen **
But it doesnt display when I do npm start.
Can anyone help me solve the issue?

const num = 9
bla
bla
num
bla bla

“const num = 9” is doing something but “num” is not.

Not sure why code pen does it. It might have something to do with the pre-processing text entered in code pen boxes, but it is not a valid assignment or a function call. It evaluates or equals the timer id returned by the setTimeout() function.

You would need to use the useCallback() hook if you wanted to have the stay along Clock() function, and you would want to use the useRef() hook to keep track of your current timer id.

import { useState, useEffect, useRef, useCallback } from "react";

function App() {
  const [timer, setTimer] = useState(1500);
  const [isActive, setIsActive] = useState(false);

  let timeoutId = useRef(null);

  const clock = useCallback(() => {
    if (timer && isActive) {
      timeoutId.current = setTimeout(() => {
        setTimer((prev) => prev - 1);
      }, 1000);
    } else {
      clearTimeout(timeoutId.current);
    }
  }, [timer, isActive]);

  const handlePlay = () => {
    clearTimeout(timeoutId.current);
    setIsActive((prev) => !prev);
  };

  const handleReset = () => {
    clearTimeout(timeoutId.current);
    setTimer(1500);
  };

  useEffect(() => {
    clock();
  }, [clock]);

  const formatTime = () => {
    return (
      `0${Math.floor(timer / 60)}`.slice(-2) + ":" + `0${timer % 60}`.slice(-2)
    );
  };

  return (
    <div className="App">
      <h1>{formatTime()}</h1>
      <div>
        <button onClick={handlePlay}>start/stop</button>
        <button onClick={handleReset}>reset</button>
      </div>
    </div>
  );
}

export default App;

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.