V
V
Vladimir2022-02-24 15:28:21
JavaScript
Vladimir, 2022-02-24 15:28:21

How to update state by timer?

Hello. Please tell me how can I update the state once per second? I have created a time counter and I need to output it to a react component, I try it like this:

const date = {
    hours: 0,
    minutes: 0,
    seconds: 0,
    isActive: false,
    start: function() {
      this.isActive = true;
      return this
    },
    stop: function() {
      this.isActive = false;
      return this
    }
  }

  function timer() {

    if(this.isActive) {
      if(this.seconds < 60) date.seconds += 1;
      else {
        this.seconds = 0;
        if(this.minutes < 60) date.minutes += 1;
        else {
          this.minutes = 0;
          this.hours += 1;
        }
      }
    }

    return this

  }

  const myTimer = timer.bind(date);
  const [timerState, setTimerState] = useState({});
  let interval;

  useEffect(() => {
    if(interval) clearInterval(interval);
    interval = setInterval(() => {
      if(clients.length > 1) {
          setTimerState(myTimer().start());
      } else {
        setTimerState(myTimer().stop());
      }
      console.log(timerState);
    }, 1000);
  }, [clients, timerState]);


But it is updated crookedly and there is a lot of spam, how can I implement this?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Shvedkov, 2022-02-24
@kosolapus

If you need exact time, then this is not the best idea. setInterval and setTimeout have lags that will show up over time.
The simplest timer is "the current time is the start time of the timer". Thus, it is necessary to store not the current position of the counter, but the time of the beginning of the countdown. But to draw it, yes, by interval.
those.:

const startTime = newDate().now()
setinterval(()=>{
formatTimeToYourNeeds(new Date().now() - startTime)
}, 1000)

In this scenario, you not only get an accurate timer, but also the ability to change it, for example, display it with the required accuracy and interval

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question