![](/img/trans.png)
[英]How to use setInterval with react useEffect hook correctly?
[英]How to call two functions in a setInterval callback within the useEffect hook
我在useEffect挂钩中运行setInterval以连续运行两个函数,但是,只有第一个函数循环。 我需要做些什么才能使第一个功能随后运行?
我什至尝试过运行两个setInterval函数并更改其延迟选项,以尝试模拟我正在寻找的连续行为。 但是它有故障,很明显我的文字效果有问题。
const myText = props.text;
const textTimeout = props.textDelay;
const funTextInterval = (textTimeout * myText.length) + 200;
const [quickText, setQuickText] = useState([]);
const displayFunText = (i) => {
setTimeout(() => {
myFunction1();
}, textTimeout * i);
};
const erraseFunText = (j) => {
setTimeout(() => {
myFunction2();
}, textTimeout * j);
};
useEffect(() => {
const loop = () => {
for (let i = 0; i < myText.length + 1; i += 1) {
displayFunText(i);
}
};
const reverseLoop = () => {
for (let j = myText.length; j > 0; j -= 1) {
erraseFunText(j);
}
};
loop();
const callLoops = () => {
reverseLoop();
loop();
};
const runLoops = useInterval(() => {
callLoops();
}, funTextInterval);
return () => {
clearInterval(runLoops);
};
}, []);
我期望reverseLoop()
首先运行,然后loop()
之后运行,但是我没有得到这种效果。
主要问题是,擦除效果的超时延迟比显示效果的最长延迟短。 认识到显示的超时和擦除效果都是一次性执行的,因此,如果希望按正确的顺序执行回调(myFunction1,myFunction2),则延迟应继续增加。
这是它如何工作的。 注释表示我必须进行更正的地方:
// Extra code to define the functions/variables which you did not provide (ignore it): const output = document.querySelector("div"); const myFunction1 = () => output.textContent = myText.slice(0, output.textContent.length+1); const myFunction2 = () => output.textContent = myText.slice(0, output.textContent.length-1); const props = { text: "This is a test", textDelay: 100 }; const useEffect = (cb) => cb(); const useState = () => []; const useInterval = setInterval; // END extra code const myText = props.text; const textTimeout = props.textDelay; const funTextInterval = (textTimeout * myText.length * 2) + 200; // 2 times (show+hide)! const [quickText, setQuickText] = useState([]); const displayFunText = (i) => { setTimeout(() => { myFunction1(); }, textTimeout * i); }; const erraseFunText = (j) => { setTimeout(() => { myFunction2(); }, textTimeout * j); }; useEffect(() => { const loop = () => { for (let i = 0; i < myText.length; i += 1) { // fix end-condition displayFunText(i); } }; const reverseLoop = () => { for (let j = myText.length; j < 2*myText.length; j += 1) { // fix to produce greater values (= delays) erraseFunText(j); } }; const callLoops = () => { // change order: loop(); reverseLoop(); }; callLoops(); // instead of loop() const runLoops = useInterval(() => { callLoops(); }, funTextInterval); return () => { clearInterval(runLoops); }; }, []);
<div id="output"></div>
您可能需要研究promise和async
功能,这可能使这种异步更易于使用(观点有所不同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.