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
User Input: Capture user input through a text field or numerical input component to accept the desired countdown duration.
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.
Countdown Logic: Implement a function that:
Converts the user-provided duration (minutes or seconds) to milliseconds.
Uses
setInterval
to periodically update thecountdownTime
state, reducing it by the millisecond interval until it reaches zero.Triggers the audio playback when
countdownTime
reaches zero.
Visual Display: Render the remaining time in a user-friendly format (e.g., minutes:seconds or seconds countdown) based on the
countdownTime
state.Audio Integration: Include an audio element with the desired audio source URL. Utilize the
play()
method when the countdown reaches zero.Start/Pause Functionality: Implement buttons or controls to allow users to start, pause, and reset the countdown timer.
Code
Explanation
useState Hooks: Manage
countdownTime
andisPlaying
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, andplay()
triggers playback at zerocountdownTime
.Start/Pause and Reset buttons: Update
isPlaying
and resetcountdownTime
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