JavaScript - How to Wait / SetTimeOut / Sleep / Delay

后端 未结 2 1174
谎友^
谎友^ 2021-02-04 13:56

This again is my Rock Paper Scissors game.

At present state the user can\'t see what\'s happening because after being prompted for input(Rock, Paper or Scissors) they ar

相关标签:
2条回答
  • 2021-02-04 14:03

    You cannot return a value for a parent function on a setTimeout, setInterval or another child function because have different scopes.

    You can use promises instead: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    Bad:

    function x () {
      setTimeout(function () {
         return "anything";
      }, 5000);
    }
    

    Using promises:

    function x () {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          resolve("anything");
        }, 5000);
      });
    }
    

    Then you can call function like:

    x()
    .then(
      function (result) {
        alert(result); // Do anything.
      }
    );
    

    PD: I have bad English, I'm sorry!.

    0 讨论(0)
  • This took me a long time to figure out but here was the solution.

    Create this function

    function sleep(miliseconds) {
        var currentTime = new Date().getTime();
        while (currentTime + miliseconds >= new Date().getTime()) {
        }
    }
    

    Add this into my code where I wanted the delay

    sleep(3000)
    
    0 讨论(0)
提交回复
热议问题