โฐ

Timer with Notifications

๐Ÿง‘โ€๐Ÿณ Cookโฑ๏ธ 20 minutes

๐Ÿ“‹ Suggested prerequisites

  • โ€ขReact
  • โ€ขuseEffect

What you'll build

An interactive countdown timer with React that uses intervals and the browser notification API. Includes buttons to start, pause, and reset, display in MM:SS format, and a browser notification when time runs out. Great for understanding useEffect and timing in React.


Step 1: Ask an AI for the timer

I need a countdown timer in React with:
- Input for minutes and seconds
- Buttons: Start, Pause, Reset
- Display format MM:SS
- Browser notification when it reaches 0
- Alert sound
- useEffect for the interval
- TypeScript and Tailwind CSS

Give me the complete code.

Timer logic

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])

Notifications

const requestPermission = async () => {
  if ('Notification' in window) {
    await Notification.requestPermission()
  }
}

const notify = () => {
  if (Notification.permission === 'granted') {
    new Notification('Time is up!', {
      body: 'Your timer has reached zero',
      icon: '/timer-icon.png'
    })
  }
}

Time format

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')}`
}

Next step

โ†’ Image Gallery