如何在setInterval回调中调用两个函数在使用效果钩中



我在使用效果钩中运行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>

您可能想研究承诺和async功能,这可能会使这种异步更易于使用(观点不同(。

相关内容

  • 没有找到相关文章

最新更新