循环数组与setInterval播放按钮,并暂停它



我想循环遍历一个带有暂停和开始按钮的数组。现在它自动播放,我不知道如何将setInterval连接到播放函数,也不知道如何停止间隔,因为我所尝试的一切只是崩溃它。也许有一个很好的库来做这个,因为我可以想象这是一件很正常的事情?如果不是,请帮助我修复我的代码,也许有更好的方法来做到这一点,如果是这样,请告诉:)码漏尝试: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>
);
}

您应该在每次渲染时删除间隔,请参见演示:

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>
);
}

https://codesandbox.io/s/throbbing-cdn-4c77nr

相关内容

  • 没有找到相关文章

最新更新