1- import React , { useState , useRef } from 'react' ;
1+ import React , { useState , useEffect , useRef } from 'react' ;
22
33function 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