Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

65
Views
How do I manage intervals with event handlers in React JS?

I am learning React JS and I started building a Pomodoro clock. I do not understand how to start a specified interval upon clicking a button and stopping the timer upon clicking a separate button. When I click "play" the timer stalls at 24:059. When I click the same button, it goes to 24:058 and jumps back to 24:059 then repeats. When I click it again, it goes to 24:057, etc.

When I remove the switch(seconds) condition in decreaseTimer() and simply insert setSeconds((seconds) => seconds - 1); the seconds decrement by 1 as expected. How do I fix this issue? I appreciate all the help and advice here. Thank you!

PomoTimer.js

import { useEffect, useState } from "react";

const PomoTimer = (props) => {
  const [seconds, setSeconds] = useState(0);
  const [intervalId, setIntervalId] = useState("");
  const [isSession, setSession] = useState(true);

  const startTimer = () => {
    let newIntervalId = setInterval(decreaseTimer, 1000);

    setIntervalId((intervalId) => newIntervalId);
  };

  const stopTimer = () => {
    clearInterval(intervalId);
  };

  const decreaseTimer = () => {
    switch (seconds) {
      case 0:
        props.onTimerMinuteChange(props.timerMinute - 1);
        setSeconds((seconds) => 59);
        break;
      default:
        setSeconds((seconds) => seconds - 1);
        break;
    }
  };

  const resetTimer = () => {
    clearInterval(intervalId);

    props.resetTimer();
    props.onPlayChange(false);

    setSeconds(0);
  };

  return (
    <section>
      <section>
        {/* <h4>{session === true ? "Session" : "Break"}</h4> */}
        <span>{props.timerMinute}</span>
        <span>:</span>
        <span>{seconds === 0 ? "00" : "0" + seconds}</span>
      </section>
      <section>
        <button onClick={startTimer}>Play</button>
        <button onClick={stopTimer}>Stop</button>
        <button onClick={resetTimer}>Refresh</button>
      </section>
    </section>
  );
};

export default PomoTimer;
7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.