React 스톱워치 구현하기(TS)

2022. 11. 17. 16:47·FE/React
반응형

스톱워치를 구현해야하는 과제가 있어서 직접 구현해보았다.

 

완성!


StopWatch.tsx

import { useState, useEffect } from 'react'

const StopWatch = () => {
  const [time, setTime] = useState(0)
  const [isRunning, setIsRunning] = useState(false)

  useEffect(() => {
    let interval: NodeJS.Timer | undefined

    if (isRunning) {
      interval = setInterval(() => {
        setTime((prevTime) => prevTime + 10)
      }, 10)
    } else {
      clearInterval(interval)
    }

    return () => clearInterval(interval)
  }, [isRunning])

  return (
    <div>
      <time>
        {`0${Math.floor((time / 60000) % 60)}`.slice(-2)} : {`0${Math.floor((time / 1000) % 60)}`.slice(-2)}
      </time>
      <div>
        <button type='button' onClick={() => setIsRunning(true)}>
          Start
        </button>
        <button type='button' onClick={() => setIsRunning(false)}>
          Stop
        </button>
        <button type='button' onClick={() => setTime(0)}>
          Reset
        </button>
      </div>
    </div>
  )
}

export default StopWatch

먼저 시간을 관리하는 time과 동작 여부를 나타내는 isRunning이라는 state를 만들어준 후, useEffect를 사용해 현재 스톱워치가 동작 중인 경우 time에 +10을 해준다.

 

현재 동작 중이지 않다면 clearInterval을 해주면 된다. 이 때 interval의 타입은 node환경의 경우 Node.Timer이고 window일 경우 number라고 한다. (이 글 참고)

 

time에서 각 단위에 맞게 시간을 계산해준 값을 리턴해주고, start, stop, reset 버튼에 각각 그에 맞는 동작을 onClick에 지정해주면 된다.

 

 

References

https://w3collective.com/react-stopwatch/

https://stackoverflow.com/questions/51376589/typescript-what-type-is-f-e-setinterval

반응형

'FE > React' 카테고리의 다른 글

[React] Storybook 사용해보기  (0) 2022.12.02
React Infinite Carousel 만들기(TS)  (1) 2022.11.24
React 다크 모드 구현하기(with Recoil, SCSS)  (0) 2022.11.06
React 프로젝트에 i18n으로 다국어 지원하기  (0) 2022.10.31
React의 LifeCycle  (0) 2021.06.30
'FE/React' 카테고리의 다른 글
  • [React] Storybook 사용해보기
  • React Infinite Carousel 만들기(TS)
  • React 다크 모드 구현하기(with Recoil, SCSS)
  • React 프로젝트에 i18n으로 다국어 지원하기
SH_Roh
SH_Roh
  • SH_Roh
    혼자공부끄적끄적
    SH_Roh
  • 전체
    오늘
    어제
    • 분류 전체보기 (159)
      • FE (39)
        • HTML, CSS (3)
        • Javascript (17)
        • React (11)
        • Next.js (4)
      • Network (1)
      • DevOps (4)
      • Git (1)
      • Trouble Shooting (24)
      • Algorithm (41)
        • Python (2)
        • Data Structure, Algorithm (7)
        • Problem Solving (31)
      • Education (23)
        • Elice AI Track (4)
        • Wanted Pre-Onboarding FE Co.. (19)
      • TIL (25)
      • Etc. (1)
        • 회고 (1)
        • 그냥저냥 (0)
  • 링크

    • Github
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
SH_Roh
React 스톱워치 구현하기(TS)
상단으로

티스토리툴바