skip to Main Content

Hello StackOverflow community.

I am just starting with learning react and I came across this challenge, where we have to display the current time, with a button to Pause/Restart the time. But the catch is on clicking the pause button it should pause the time, and again on clicking the button it should restart the clock from the same paused time.

Please note that the clock should start from the paused time and not the current time.

Below is my code.

import "./App.css";
import { useEffect, useState } from "react";

function App() {
  const [time, setTime] = useState(new Date().toLocaleTimeString());
  const [pause, setPause] = useState(false);

  useEffect(() => {
    let timer = setInterval(() => {
      if (!pause) {
        setTime(new Date().toLocaleTimeString());
      }
    }, 1 * 1000);
    return () => clearInterval(timer);
  }, [pause]);

  return (
    <div className="m-2 p-2 flex">
      <h1 className="m-1 p-1">{time}</h1>
      <button
        className="m-1 p-2 bg-slate-200 rounded-lg shadow-lg font-semibold"
        onClick={() => setPause(!pause)}
      >
        {pause ? "Start" : "Pause"}
      </button>
    </div>
  );
}

export default App;

I am not able to get the logic on how to restart the clock from the paused time and not the current time.
Any help is appreciated.

2

Answers


  1. The following pseudocode helps to achieve running the time from where it was paused.

    • On clicking the pause button, store the current time in a state variable
    • Change the pause state variable
    • This enables the useEffect
    • Here, if paused, use a timer to record till the next time user click the resume
    • On clicking resume, change the pause state variable and display the current time subtracting the recorded time from timer.
    • In the useEffect, checking if its resume, stop the timer.
    Login or Signup to reply.
  2. Just store the time on load. Then increment it inside code

    
    import { useEffect, useState } from "react";
    
    function App() {
      const [time, setTime] = useState(new Date());
      const [pause, setPause] = useState(false);
    
      function pauseHandler(){
        setPause(!pause)
      }
    
      useEffect(() => {
        let timer = setInterval(() => {
          if (!pause) {
            let t = time.setSeconds(time.getSeconds() + 1)
            setTime(new Date(t));
          }
        }, 1 * 1000);
        return () => clearInterval(timer);
      }, [pause]);
    
      return (
        <div className="m-2 p-2 flex">
          <h1 className="m-1 p-1">{time.toLocaleTimeString()}</h1>
          <button
            className="m-1 p-2 bg-slate-200 rounded-lg shadow-lg font-semibold"
            onClick={() => pauseHandler()}
          >
            {pause ? "Start" : "Pause"}
          </button>
        </div>
      );
    }
    
    export default App;
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search