【问题标题】:Create time between execution of 2 functions(plain javascript)在执行 2 个函数之间创建时间(纯 javascript)
【发布时间】:2019-11-08 03:31:49
【问题描述】:

我想在我的爆炸函数和重置函数之间有一个设定的时间,如果我没有设定的时间,代码在执行函数之后快速执行重置函数。这使得爆炸基本上是看不见的。我尝试在重置功能上设置超时,但这并没有改变任何东西。

代码如下:

  function loop(){
    //game code up here
    if(out){
      //run explode for certain amount of time then call reset function
      explode();
      //setTimeout(reset, time)
      reset();
    }
  }
  setInterval(loop, 10)

【问题讨论】:

    标签: javascript timing


    【解决方案1】:

    在 JavaScript 1.7 中,使用带有 async.js 的 yield,您可以执行以下操作:

        function loop(){
        //game code up here
        if(out){
          //run explode for certain amount of time then call reset function
          explode();
          //setTimeout(reset, time)
          yield to.sleep(.500)
          reset();
        }
      }
    

    如果你只想使用纯javascript,你可以尝试以下,

    function loop() {
        //game code up here
        if (out) {
            explode();
        }
    }
    
    function explode() {
        //explode code goes here
        setTimeout(reset, 3000);
    }
    loop();
    

    【讨论】:

    • 如果 async.js 是一个库,我怎么能得到它?
    • 我在回答中添加了纯 JavaScript 方式
    【解决方案2】:

    正如上面答案中提到的@Channa,setTimeout 将在 1000 毫秒后执行您的重置功能。如果你像这样包装它会更好,否则你的重置功能将立即运行。

    setTimeout(function() { reset(); }, 1000);
    

    另外,如果你想重复调用你的函数,可以使用this。

    setInterval(reset,1000);
    

    setInterval 将在每 1000 毫秒后调用您的重置函数。

    【讨论】:

    • 更正:我想在一定时间内重复调用explode函数几次,因为explode没有渲染。
    • 这是逻辑思维 :) 花点时间思考。
    猜你喜欢
    • 2019-09-30
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    相关资源
    最近更新 更多