Skip to content

Commit c30c6ce

Browse files
committed
feat: 🎸 Create timer in js
1 parent 3ec86ce commit c30c6ce

File tree

3 files changed

+43
-4
lines changed

3 files changed

+43
-4
lines changed

2024 Prep/machine_coding/react/src/App.tsx

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import './App.css'
2-
import { BatchingStates } from './components'
2+
import { CountDownTimer } from './components'
33

44
function App() {
55
return (
66
<div className="container">
77
<h1>Vite + React</h1>
8-
<div>{/* <FileExplorer data={fileExplorerData} /> */}</div>
9-
<BatchingStates />
8+
<CountDownTimer seconds={20} />
109
</div>
1110
)
1211
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { useEffect, useState } from 'react'
2+
3+
interface ICountDownTimerProps {
4+
seconds: number
5+
}
6+
export default function CountDownTimer(props: ICountDownTimerProps) {
7+
const { seconds = 10 } = props
8+
const [sec, setSec] = useState<number>(seconds)
9+
10+
useEffect(() => {
11+
const timerInstance = setInterval(() => {
12+
setSec(sec => sec - 1)
13+
}, 1000)
14+
15+
// In React, it's important to clean up any resources that your component uses when it is unmounted or when the dependencies of your useEffect hook change. If you don't clean up resources like intervals, timeouts, or subscriptions, they can continue running even after your component is removed from the DOM, which can lead to memory leaks or unexpected behavior.
16+
17+
// By returning a cleanup function from the useEffect hook with clearInterval(timerInstance), you ensure that the interval is cleared when the component is unmounted or when the dependencies change.
18+
19+
// This helps to prevent memory leaks and ensures that your application behaves as expected.
20+
21+
return () => clearInterval(timerInstance)
22+
}, [])
23+
24+
return (
25+
<div
26+
style={{
27+
display: 'flex',
28+
flexDirection: 'column',
29+
justifyContent: 'center',
30+
alignItems: 'center',
31+
}}
32+
>
33+
<h2>CountDown Timer</h2>
34+
<h4>
35+
current time: <b>{sec}</b>
36+
</h4>
37+
</div>
38+
)
39+
}

2024 Prep/machine_coding/react/src/components/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@ import Loader from './Loader'
22
import InfiniteScroll from './InfiniteScroll'
33
import FileExplorer from './FileExplorer'
44
import BatchingStates from './BatchingStates'
5+
import CountDownTimer from './Timer'
56

6-
export { Loader, FileExplorer, InfiniteScroll, BatchingStates }
7+
export { Loader, FileExplorer, InfiniteScroll, BatchingStates, CountDownTimer }

0 commit comments

Comments
 (0)