Answers for "useEffect time elapsed"

0

useEffect time elapsed

import React, { useState, useEffect } from 'react';

const Timer = () => {
  const [seconds, setSeconds] = useState(0);
  const [isActive, setIsActive] = useState(false);

  function toggle() {
    setIsActive(!isActive);
  }

  function reset() {
    setSeconds(0);
    setIsActive(false);
  }

  useEffect(() => {
    let interval = null;
    if (isActive) {
      interval = setInterval(() => {
        setSeconds(seconds => seconds + 1);
      }, 1000);
    } else if (!isActive && seconds !== 0) {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isActive, seconds]);

  return (
    <div className="app">
      <div className="time">
        {seconds}s
      </div>
      <div className="row">
        <button className={`button button-primary button-primary-${isActive ? 'active' : 'inactive'}`} onClick={toggle}>
          {isActive ? 'Pause' : 'Start'}
        </button>
        <button className="button" onClick={reset}>
          Reset
        </button>
      </div>
    </div>
  );
};

export default Timer;
Posted by: Guest on September-09-2020
0

useEffect time elapsed

const Clock = ({ dispatch, inProgress, ticksElapsed }) => {
  React.useEffect(() => {
    const progressTimer = setInterval(function () {
      inProgress && dispatch({ type: 'CLOCK_RUN' });
    }, 500);
    return () =>
      //inprogress is stale so when it WAS true
      //  it must now be false for the cleanup to
      //  be called
      inProgress && clearInterval(progressTimer);
  }, [dispatch, inProgress]);

  return <h1>{ticksElapsed}</h1>;
};

const App = () => {
  const [inProgress, setInProgress] = React.useState(false);
  const [ticksElapsed, setTicksElapsed] = React.useState(0);
  const dispatch = React.useCallback(
    () => setTicksElapsed((t) => t + 1),
    []
  );
  return (
    <div>
      <button onClick={() => setInProgress((p) => !p)}>
        {inProgress ? 'stop' : 'start'}
      </button>
      <Clock
        inProgress={inProgress}
        dispatch={dispatch}
        ticksElapsed={ticksElapsed}
      />
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));
Posted by: Guest on August-20-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language