Closed3

カウントダウンタイマーのWebフロントエンド実装

Kazuki YonemotoKazuki Yonemoto

Reactで実装する場合

シンプルな実装であれば秒数を初期値として与え、setIntervalでカウントダウンしていく方法が良さそう。

useCountDownInterval.ts
import { useEffect } from 'react'

const useCountDownInterval = (
  countTime: number | null,
  setCountTime: (arg0: number) => void,
) => {
  useEffect(() => {
    const countDownInterval = setInterval(() => {
      if (countTime === 0) {
        clearInterval(countDownInterval)
      }
      if (countTime && countTime > 0) {
        setCountTime(countTime - 1)
      }
    }, 1000)
    return () => {
      clearInterval(countDownInterval)
    }
  }, [countTime])
}

export { useCountDownInterval }
Countdown.tsx
import { useState } from 'react';
import { useCountDownInterval } from '@/hooks/useCountDownInterval';

export const Countdown  = () => {
  const [countTime, setCountTime] = useState<number>(180)
  useCountDownInterval(countTime, setCountTime)
    return (
      <p>ゲーム残り時間: {Math.floor(countTime / 60)}{countTime % 60}</p>
    )
}
このスクラップは2022/07/05にクローズされました