📊 Progress Bar with Controls
Category: machine-coding
Difficulty: medium
Below is an example React component for a progress bar that has Start, Pause, Stop, and Reset buttons. The component uses a timer (setInterval) to update the progress value, and different buttons change the component's state: Explanation State Management : progress (0–100) tracks the bar width. status indicates if the progress is "idle", "running", "paused", "stopped", or "completed". Timer Control : When Start is clicked, if not already running or stopped, an interval is set that increments progress. Pause clears the interval, keeping the current progress. Stop clears the interval and locks the progress (cannot resume). Reset clears any timer and resets progress and status. Auto-complete : When progress reaches 100%, the interval is cleared and status becomes "completed". Code ```jsx import React, { useState, useRef, useEffect } from 'react'; function ProgressBar() { const [progress, setProgress] = useState(0); const [status, setStatus] = useState("idle"); // idle, running, paused, stopped, completed const intervalRef = useRef(null); // Start or resume progress const startProgress = () => { // If already running or completed/stopped, do nothing if (status === "running" status === "completed" status === "stopped") return; setStatus("running"); intervalRef.current = setInterval(() => { setProgress(prev => { if (prev >= 100) { clearInterval(intervalRef.current); setStatus("completed"); return 100; } return prev + 1; // Increment progress by 1% per tick }); }, 100); // Update every 100ms }; // Pause the progress const pauseProgress = () => { if (status === "running") { clearInterval(intervalRef.current); setStatus("paused"); } }; // Stop the progress completely (cannot be resumed until reset) const stopProgress = () => { if (status === "running" status === "paused") { clearInterval(intervalRef.current); setStatus("stopped"); } }; // Reset to initial state const resetProgress = () => { clearInterval(intervalRef.current); setProgress(0); setStatus("idle"); };...