Lo que vas a construir
Un countdown timer interactivo con React que usa intervalos y la API de notificaciones del navegador. Incluye botones para iniciar, pausar y reiniciar, display en formato MM:SS, y una notificacion del navegador cuando el tiempo termina. Excelente para entender useEffect y el manejo de tiempo en React.
Paso 1: Pídele a una IA el timer
Necesito un countdown timer en React con:
- Input para minutos y segundos
- Botones: Iniciar, Pausar, Reiniciar
- Display formato MM:SS
- Notificación del navegador cuando llegue a 0
- Sonido de alerta
- useEffect para el intervalo
- TypeScript y Tailwind CSS
Dame el código completo.
Lógica del timer
const [timeLeft, setTimeLeft] = useState(0)
const [isRunning, setIsRunning] = useState(false)
useEffect(() => {
if (!isRunning || timeLeft <= 0) return
const interval = setInterval(() => {
setTimeLeft(prev => {
if (prev <= 1) {
setIsRunning(false)
notify()
return 0
}
return prev - 1
})
}, 1000)
return () => clearInterval(interval)
}, [isRunning, timeLeft])
Notificaciones
const requestPermission = async () => {
if ('Notification' in window) {
await Notification.requestPermission()
}
}
const notify = () => {
if (Notification.permission === 'granted') {
new Notification('¡Tiempo terminado!', {
body: 'Tu timer ha llegado a cero',
icon: '/timer-icon.png'
})
}
}
Formato de tiempo
const formatTime = (seconds: number): string => {
const mins = Math.floor(seconds / 60)
const secs = seconds % 60
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}