如何在 useEffect 钩子内的 setInterval 回调中调用两个函数 [英] How to call two functions in a setInterval callback within the useEffect hook

查看:52
本文介绍了如何在 useEffect 钩子内的 setInterval 回调中调用两个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 useEffect 钩子中运行 setInterval 来连续运行两个函数,但是,只有第一个函数循环.我需要做什么才能运行第一个函数,然后运行第二个函数?

I am running setInterval in the useEffect hook to run two functions consecutively, however, only the first function loops. What do I need to do to get the first function to run followed by the second?

我什至尝试运行两个 setInterval 函数并更改它们的延迟选项,以尝试模拟我正在寻找的连续行为.但是出现了小故障,很明显我的文字效果有问题.

I have even tried having two setInterval functions running and changing their delay options to try and simulate the consecutive behavior I am looking for. But it glitches and it is quite obvious that there is a problem with my text effect.

   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() 运行,但我没有得到那种效果.

I expect the reverseLoop() to run first then loop() to run after, but I am not getting that effect.

推荐答案

主要问题是您擦除效果的超时延迟比显示效果的最长延迟要短.意识到显示超时和擦除效果都是一次性执行的,因此如果您希望回调(myFunction1,myFunction2)按正确顺序执行,延迟应该不断增加.

The main issue is that your time out delays for erasing effects are shorter than the longest delay for the display effect. Realise that the timeouts for the display and the erasing effect are executed all in one go, so the delays should keep increasing if you want the callbacks (myFunction1, myFunction2) to be executed in proper order.

这是它的工作原理.评论指出我必须更正的地方:

Here is how it could work. Comments denote where I had to make corrections:

// 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>

您可能想要研究 promises 和 async 函数,这可能会使这种异步更容易使用(意见不同).

You may want to look into promises and async functions, which might make this kind of asynchrony easier to work with (opinions differ).

这篇关于如何在 useEffect 钩子内的 setInterval 回调中调用两个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆