I am unable to stop the loop after a conditional. I am able to stop the interval after a button click but unable to stop it after a conditional such as loop increments. This simple example tries to stop the interval loop after 5 loops.
Any solutions would be much appreciated!
JavaScript
x
54
54
1
import React, { useState } from 'react';
2
3
let gameLoop: any;
4
5
function App() {
6
const [loopCount, setLoopCount] = useState(0);
7
const [running, setRunning] = useState(true);
8
9
const gameLogic = () => {
10
console.log('Game logic!')
11
}
12
13
const loop = () => {
14
gameLogic();
15
setLoopCount(prev => {
16
const newCount = prev + 1;
17
console.log(newCount)
18
return newCount
19
});
20
21
// Stop the loop on a conditional
22
if(loopCount >= 5){
23
clearInterval(gameLoop)
24
}
25
}
26
27
const handleStartButtonClick = () => {
28
gameLoop = setInterval(loop, 1000)
29
setRunning(true);
30
}
31
32
const handleStopButtonClick = () => {
33
clearInterval(gameLoop);
34
setRunning(false);
35
}
36
37
const handleResetButtonClick = () => {
38
setLoopCount(0);
39
console.clear();
40
}
41
42
return (
43
<div className="App">
44
<div>
45
<button onClick={handleStartButtonClick}>Start</button>
46
<button onClick={handleStopButtonClick}>Stop</button>
47
<button onClick={handleResetButtonClick}>Reset</button>
48
</div>
49
</div>
50
);
51
}
52
53
export default App;
54
Advertisement
Answer
The solution is to put the conditional at the component level, not in the loop method.
JavaScript
1
56
56
1
import React, { useState } from 'react';
2
3
let gameLoop: any;
4
5
function App() {
6
const [loopCount, setLoopCount] = useState(0);
7
const [running, setRunning] = useState(true);
8
9
const gameLogic = () => {
10
console.log('Game logic!')
11
}
12
13
const loop = () => {
14
gameLogic();
15
setLoopCount(prev => {
16
const newCount = prev + 1;
17
console.log(newCount)
18
return newCount
19
});
20
21
22
}
23
//MOVE OUTSIDE GAME LOOP
24
// Stop the loop on a conditional
25
if(loopCount >= 5){
26
clearInterval(gameLoop)
27
}
28
29
const handleStartButtonClick = () => {
30
gameLoop = setInterval(loop, 1000)
31
setRunning(true);
32
}
33
34
const handleStopButtonClick = () => {
35
clearInterval(gameLoop);
36
setRunning(false);
37
}
38
39
const handleResetButtonClick = () => {
40
setLoopCount(0);
41
console.clear();
42
}
43
44
return (
45
<div className="App">
46
<div>
47
<button onClick={handleStartButtonClick}>Start</button>
48
<button onClick={handleStopButtonClick}>Stop</button>
49
<button onClick={handleResetButtonClick}>Reset</button>
50
</div>
51
</div>
52
);
53
}
54
55
export default App;
56