首页 > 解决方案 > 当 setTimeout 执行多次时,希望覆盖之前的 setTimeout

问题描述

我正在制作可以切换显示或隐藏的视频控件。
视频控件的功能将在 3 秒后消失。
但是当多次执行setTimeout时,它不会在3秒内消失。
我想让它在 3 秒内消失,甚至执行几次。

我的代码是:

const [showVideoControls, setShowVideoControls] = useState(false);
const [secondCall, setSecondCall] = useState(false);
let timeoutID;

 function setUpVideoControls() {
    if (!showVideoControls) {
      setShowVideoControls(true);
    } else {
      setShowVideoControls(false);
    }
  }

  function offVideoControls() {
    return new Promise(resolve => {
      resolve(setSecondCall(true));
    });
  }

  function callUnified() {
    if (secondCall) {
      return new Promise(resolve => {
        resolve(unified());
      });
    }
  }

  function tmp() {
    return new Promise(resolve => {
      resolve(unified2());
    });
  }

  function unified() {
    clearTimeout(timeoutID);
    setSecondCall(false);
  }

  function unified2() {
    timeoutID = setTimeout(function () {
      setShowVideoControls(false);
    }, 3000);
  }

  async function callingFirstTime() {
    await tmp();
    await offVideoControls();
  }

  async function callingAfterSecondTime() {
    await callUnified();
  }

...

<View style={{ width: '100%', height: '100%' }}>
  <TouchableWithoutFeedback
    onPress={() => {
      if (secondCall) {
        callingAfterSecondTime();
      }
      setUpVideoControls();
      callingFirstTime();
      }}>
    <Text
      style={{
        flex: 1,
       }}>
      {''}
    </Text>
  </TouchableWithoutFeedback>
</View>

我的代码的功能是:

①执行 setTimeout
②clearTimeout(shold be cancelled before setTimeout)
③执行 setTimeout

我觉得我的代码没问题,但是效果不好。
我该如何解决?
您可以提供的任何建议将不胜感激。

标签: javascriptreactjsreact-nativesettimeout

解决方案


推荐阅读