【问题标题】:How to maintain a specific time duration between calling two functions in JavaScript?如何在 JavaScript 中调用两个函数之间保持特定的持续时间?
【发布时间】:2023-01-20 18:53:38
【问题描述】:

我想创建一个调用一个函数的代码,比如toStart(),然后恰好在两秒后调用另一个函数toStop(),第一个函数被调用,直到我按下另一个按钮nowComplete。我学习了一个函数setInterval(),但它只在页面加载每两秒后调用函数toStop(),它不依赖于函数toStart()启动的时间。我怎样才能摆脱这个?

<button type="button" onclick="nowend">Now Complete</button>
<script>
function toStart(){
  //do something here
  setInterval(toStop,2000);
}

function toStop(){
  //do Something here
}
function nowend(){
//Stop both the functions here to work
}

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    下面的代码将在控制台中记录“启动”,然后在 2 秒后“停止”。如果在 2 秒之前按下“nowComplete”按钮,超时将被取消并且“停止”将不会被记录。参考setTimeoutclearTimeout

    <button type="button" onclick="nowEnd">Now Complete</button>
    <script>
    let timeoutId;
    
    function toStart(){
      console.log('started');
      timeoutId = setTimeout(toStop, 2000);
    }
    
    function toStop(){
      console.log('stopped');
    }
    function nowEnd(){
      clearTimeout(timeoutId);
    }
    
    toStart();
    </script>
    

    【讨论】:

      【解决方案2】:

      你可以这样做: setTimeout() 是 setInterval() 的对应物。

      function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
      
      sleep(2000)
        .then(() => toStart())
        .then(() => sleep(2000))
        .then(() => toStop())
      

      使用此功能,您会更加灵活。

      如果你想阅读更多关于不同方法的信息,你可以实现你的目标:https://www.sitepoint.com/delay-sleep-pause-wait/

      【讨论】:

        【解决方案3】:

        您可以在第一个函数上使用 setTimeOut,将第二个函数用作回调,如下所示:

        function toStart(){
           console.log('started') 
          setTimeout(toStop,2000);
        }
        
        function toStop(){
           console.log('Stopped') 
        }
        &lt;button type="button" onclick="toStart()"&gt;Now Complete&lt;/button&gt;

        【讨论】:

          猜你喜欢
          • 2021-01-03
          • 2014-02-28
          • 2016-08-20
          • 2020-06-28
          • 2018-11-23
          • 2023-03-25
          • 1970-01-01
          相关资源
          最近更新 更多