Closed3
カウントダウンタイマーのWebフロントエンド実装
やりたいこと
Webゲーム制作でユーザーに制限時間を設けさせる際にカウントダウンタイマーを作りたい。
カウントダウンタイマーをJS, HTML, CSSで表現する方法について考える。
参考
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>
)
}
Reactで実装する場合(パッケージ利用)
要件が複雑になりそうなら react-timer-hook
というカスタムフックがあったのでこういうのを使うと楽に実装できそう。
このスクラップは2022/07/05にクローズされました