Skip to content

Commit ac24b11

Browse files
authored
useEffect
1 parent 63091f6 commit ac24b11

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/TrainSimulator.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useState, useRef } from 'react';
1+
import React, { useState, useEffect, useRef } from 'react';
22

33
function TrainSimulator() {
44
const [speed, setSpeed] = useState(0);
@@ -7,16 +7,26 @@ function TrainSimulator() {
77
const [isRunning, setIsRunning] = useState(false);
88
const intervalRef = useRef(null);
99

10+
useEffect(() => {
11+
if (isRunning) {
12+
intervalRef.current = setInterval(() => {
13+
console.log({ speed, throttle, pressure });
14+
}, 1000);
15+
} else {
16+
clearInterval(intervalRef.current);
17+
}
18+
19+
return () => {
20+
clearInterval(intervalRef.current);
21+
};
22+
}, [isRunning, speed, throttle, pressure]);
23+
1024
const startSimulation = () => {
1125
setIsRunning(true);
12-
intervalRef.current = setInterval(() => {
13-
console.log({ ...speed, ...throttle, ...pressure });
14-
}, 1000);
1526
};
1627

1728
const stopSimulation = () => {
1829
setIsRunning(false);
19-
clearInterval(intervalRef.current);
2030
};
2131

2232
const handleSpeedChange = (event) => {
@@ -32,7 +42,6 @@ function TrainSimulator() {
3242
};
3343

3444

35-
3645
return (
3746
<div>
3847
<div>

0 commit comments

Comments
 (0)