Skip to content

Instantly share code, notes, and snippets.

@deepanshumehtaa
Last active July 31, 2024 11:03
Show Gist options
  • Save deepanshumehtaa/286bab009f4df00d46cb64fbfc2048ce to your computer and use it in GitHub Desktop.
Save deepanshumehtaa/286bab009f4df00d46cb64fbfc2048ce to your computer and use it in GitHub Desktop.
React CountDown Timer
import React, { Fragment } from 'react';
import { useState, useEffect } from 'react';
export default function Solution() {
const [totalSeconds, setTotalSeconds] = useState(0);
const [isPaused, setPaused] = useState(true); // Start with paused state
const [time_str, setTime_str] = useState("00:00");
function MyStart() {
let seconds = parseInt(document.getElementById("secs").value);
let minutes = parseInt(document.getElementById("mins").value);
setTotalSeconds(minutes * 60 + seconds);
setPaused(false);
}
function currentStrTime() {
if (totalSeconds <= 0) {
setTime_str("00:00");
setPaused(true);
} else {
let minutes = Math.floor(totalSeconds / 60);
let seconds = totalSeconds % 60;
setTime_str(
`${minutes > 9 ? minutes : "0" + minutes}:${seconds > 9 ? seconds : "0" + seconds}`
);
}
}
function MyRest() {
setTime_str("00:00");
setPaused(true);
setTotalSeconds(0);
}
useEffect(() => {
const intervalId = setInterval(() => {
if (!isPaused && totalSeconds > 0) {
setTotalSeconds((prev) => prev - 1);
currentStrTime();
}
}, 1000);
return () => clearInterval(intervalId);
}, [isPaused, totalSeconds]);
// we can also use this (good example of Pub sub)
// useEffect(() => {
// // Call currentStrTime function whenever totalSeconds changes
// currentStrTime();
// }, [totalSeconds]);
return (
<Fragment>
<label>
<input id="mins" type="number" />
Minutes
</label>
<label>
<input id="secs" type="number" />
Seconds
</label>
{/* Remember: `MyStart` & `MyRest` are not state functions hence called directly */}
<button onClick={MyStart}>START</button>
<button onClick={() => setPaused(!isPaused)}>PAUSE / RESUME</button>
<button onClick={MyRest}>RESET</button>
<h1 data-testid="running-clock">{time_str}</h1>
</Fragment>
);
} // component end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment