5 - Countdown Timer with Audio

Description

Develop a React application featuring a countdown timer that visually displays the remaining time and plays an audio cue upon reaching zero. Users should be able to set the desired countdown duration in minutes or seconds.

Algorithm

  1. User Input: Capture user input through a text field or numerical input component to accept the desired countdown duration.

  2. State Management: Utilize React's useState hook to manage two state variables:

    • countdownTime: Stores the remaining time in milliseconds.

    • isPlaying: Indicates whether the countdown is active or paused.

  3. Countdown Logic: Implement a function that:

    • Converts the user-provided duration (minutes or seconds) to milliseconds.

    • Uses setInterval to periodically update the countdownTime state, reducing it by the millisecond interval until it reaches zero.

    • Triggers the audio playback when countdownTime reaches zero.

  4. Visual Display: Render the remaining time in a user-friendly format (e.g., minutes:seconds or seconds countdown) based on the countdownTime state.

  5. Audio Integration: Include an audio element with the desired audio source URL. Utilize the play() method when the countdown reaches zero.

  6. Start/Pause Functionality: Implement buttons or controls to allow users to start, pause, and reset the countdown timer.

Code

import React, { useState, useEffect } from 'react';

function CountdownTimerApp() {
  const [countdownTime, setCountdownTime] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);

  const audioRef = useRef(null);

  useEffect(() => {
    let interval;
    if (isPlaying && countdownTime > 0) {
      interval = setInterval(() => setCountdownTime(countdownTime - 1000), 1000);
    } else if (!isPlaying || countdownTime === 0) {
      clearInterval(interval);
      if (countdownTime === 0) audioRef.current.play();
    }
    return () => clearInterval(interval);
  }, [countdownTime, isPlaying]);

  const handleStartStop = () => setIsPlaying(!isPlaying);
  const handleReset = () => setCountdownTime(0);

  const getFormattedTime = () => {
    const minutes = Math.floor(countdownTime / 60000);
    const seconds = Math.floor((countdownTime % 60000) / 1000);
    return `${minutes ? minutes + ':' : ''}${seconds.toString().padStart(2, '0')}`;
  };

  return (
    <div className="countdown-timer-app">
      <h1>Countdown Timer</h1>
      <input
        type="number"
        placeholder="Set duration (minutes or seconds)"
        onChange={(e) => setCountdownTime(e.target.value * 60000)}
      />
      <button onClick={handleStartStop}>{isPlaying ? 'Pause' : 'Start'}</button>
      <button onClick={handleReset}>Reset</button>
      <p>{getFormattedTime()}</p>
      <audio ref={audioRef} src="path/to/audio.mp3" preload="auto" />
    </div>
  );
}

export default CountdownTimerApp;

Explanation

  • useState Hooks: Manage countdownTime and isPlaying state for remaining time and countdown status.

  • useEffect Hook: Triggers logic updates based on state changes. It manages the timer interval, audio playback, and cleanup.

  • setInterval: Defines the recurring timer update with 1-second intervals.

  • Audio Integration: audioRef holds the audio element, and play() triggers playback at zero countdownTime.

  • Start/Pause and Reset buttons: Update isPlaying and reset countdownTime to respective actions.

  • getFormattedTime function: Converts milliseconds to user-friendly minutes:seconds format for display.

Additional Notes

  • This code provides a basic implementation. You can enhance it by:

    • Offering customization options for audio source and timer interval.

    • Adding visual progress indicators like a progress bar or countdown text color changes.

    • Implementing multiple audio cues for different countdown stages (e.g., nearing completion).

Last updated