I want to loop through a array with a pause and a start button. Right now it automatically plays and I am not sure how to connect the setInterval to the play function and not sure how to stop the interval as everything I try just crashes it. Maybe there is a good a library for doing this as I can imagine this is quite a normal thing to do? If not please help me fix my code, maybe there is better ways to do this if so please tell :) Codesandbox attempt: https://codesandbox.io/s/modern-dream-4kldkg?file=/src/App.js
import "./styles.css";
import { useState } from "react";
export default function App() {
const array = [1, 2, 3, 5, 6, 7];
const [current, setCurrent] = useState(0);
const play = () => {
setCurrent(current 1);
};
const pause = () => {};
const reset = () => {
setCurrent(0);
};
var intervalID = setInterval(function () {
if (current >= array.length) {
setCurrent(0);
}
setCurrent(current 1);
}, 5000);
return (
<div className="App">
<button onClick={() => play()}>play</button>
<br></br>
<button onClick={() => pause()} style={{ marginTop: "5px" }}>
Pause
</button>
<br></br>
<button onClick={() => reset()} style={{ marginTop: "5px" }}>
Reset
</button>
<br></br>
<h1>{array[current]}</h1>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
CodePudding user response:
You should remove the interval on each render, please see the demo:
import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
const array = [1, 2, 3, 4, 5, 6, 7];
const [current, setCurrent] = useState(0);
const [paused, setPaused] = useState(true);
const play = () => {
setPaused(false);
};
const resume = () => {
setPaused(false);
};
const pause = () => {
setPaused(true);
};
const reset = () => {
setCurrent(0);
setPaused(true);
};
useEffect(
function () {
var timeout;
if (!paused) {
timeout = setTimeout(function () {
const next = current < array.length - 1 ? current 1 : 0;
setCurrent(next);
}, 1000);
}
return function () {
clearTimeout(timeout);
};
},
[paused, current, array.length]
);
return (
<div className="App">
<button onClick={() => play()}>play</button>
<br></br>
<button onClick={() => pause()} style={{ marginTop: "5px" }}>
Pause
</button>
<button onClick={() => resume()} style={{ marginTop: "5px" }}>
Resume
</button>
<br></br>
<button onClick={() => reset()} style={{ marginTop: "5px" }}>
Reset
</button>
<br></br>
<h1>{array[current]}</h1>
</div>
);
}