DEV Community

Saba beigi
Saba beigi

Posted on • Edited on

Count Down Timer hooks in react hooks

import React,{useState, useEffect} from 'react';
function Timer({Min, Sec, onTimeout}) {
  const [seconds, setSeconds] = useState(Sec);
  const [minutes, setMinutes] = useState(Min);

  function updateTime() {
    if (minutes === 0 && seconds === 0) {
      onTimeout(true);
    } else {
      if (seconds === 0) {
        setMinutes((minutes) => minutes - 1);
        setSeconds(59);
      } else {
        setSeconds((seconds) => seconds - 1);
      }
    }
  }
  useEffect(() => {
    const token = setTimeout(updateTime, 1000);
    return function cleanUp() {
      clearTimeout(token);
    };
  });
  return (
    <div>
      {minutes === 0 && seconds === 0 ? null : (
        <h6>
          {minutes}:{seconds < 10 ? `0${seconds}` : seconds}
        </h6>
      )}
    </div>
  );
}

export default Timer;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)