5 - Countdown Timer with Audio
Description
Create a React application that displays a countdown timer with an audio cue when the timer reaches zero.
Algorithm
Initialize state variables to store the timer duration and a flag for the audio cue.
Render a countdown timer that updates every second.
Define a function to play an audio cue when the timer reaches zero.
Use the
setIntervalfunction to update the timer and play the audio cue when necessary.
Classes
CountdownTimer: A React component that manages the timer state and renders the countdown timer and audio cue.
Code
import React, { useState, useEffect } from 'react';
function CountdownTimer() {
const [timer, setTimer] = useState(10); // initial timer duration
const [playAudio, setPlayAudio] = useState(false);
const handleTimerUpdate = () => {
setTimer((prevTimer) => prevTimer - 1);
if (timer === 0) {
setPlayAudio(true);
}
};
useEffect(() => {
const intervalId = setInterval(handleTimerUpdate, 1000);
return () => clearInterval(intervalId);
}, []);
const playAudioCue = () => {
const audio = new Audio('audio_file.mp3'); // replace with your audio file
audio.play();
};
return (
<div>
<p>Countdown: {timer}</p>
{playAudio && playAudioCue()}
</div>
);
}
export default CountdownTimer;
Explanation
The code defines a CountdownTimer component that utilizes the useState hook to initialize state variables for the timer duration and an audio cue flag. A countdown timer is rendered, updating every second using the setInterval function. When the timer reaches zero, the playAudio flag is set to true, triggering the audio cue to play.
Possible Future Enhancements
Customize the audio cue by allowing users to upload their own audio files.
Implement a reset button to restart the timer.
Display a visual indicator when the timer reaches zero.
Integrate with a game or quiz application to use the countdown timer as a time limit.
Last updated