JS同步函数在setTimeout中没有执行小超时

时间:2017-08-23 14:08:00

标签: javascript

为什么这段代码没有显示"你按下取消"在第一次取消后?

确认框不允许" hi"从显示。

<!DOCTYPE html>
<html>
  <body>
    <h2>JavaScript Confirm Box</h2>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>
    <script>
      function myFunction() {
        document.getElementById("demo").innerHTML = "hi";
        setTimeout(confirmOperation, 0, "Please, press a button!");
      }
      function confirmOperation(message) {
        var txt;
        if (confirm(message) == true) {
          txt = "You pressed OK!";
          document.getElementById("demo").innerHTML = txt;
          return true;
        } else {
          txt = "You pressed Cancel!";
          document.getElementById("demo").innerHTML = txt;
          setTimeout(confirmOperation, 0, "Please, press a button!");
          return false;
        }
      }
    </script>
  </body>
</html>

2 个答案:

答案 0 :(得分:0)

你是递归调用函数延迟0秒。设置稍微延迟,例如5mS

document.getElementById("demo").innerHTML = txt;
setTimeout(confirmOperation, 0, "Please, press a button!");
                             ^^

将其更改为

document.getElementById("demo").innerHTML = txt;
setTimeout(confirmOperation, 5, "Please, press a button!");
                             ^^

function myFunction() {
      document.getElementById("demo").innerHTML = "hi";
      setTimeout(confirmOperation, 0, "Please, press a button!");
    }

    function confirmOperation(message) {
      var txt;
      if (confirm(message) == true) {
        txt = "You pressed OK!";
        document.getElementById("demo").innerHTML = txt;
        return true;
      } else {
        txt = "You pressed Cancel!";
        console.log(txt);
        document.getElementById("demo").innerHTML = txt;
        setTimeout(confirmOperation, 5, "Please, press a button!");
        return false;
      }
    }
<body>

  <h2>JavaScript Confirm Box</h2>


  <button onclick="myFunction()">Try it</button>

  <p id="demo"></p>


</body>

答案 1 :(得分:0)

首先,您似乎没有定义&#34;消息&#34;在你的函数confirmOperation(消息)。

其次,您使用的是setTimeout(...)错误。你需要传递一个函数而没有括号。

第三,你的dom元素上没有eventlistener。

这是一个非常漂亮的例子:https://jsfiddle.net/kmxr6f21/

<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>

function myFunction() {
  console.log("Clicked");
  document.getElementById("demo").innerHTML = "hi";
  setTimeout(function() {
    confirmOperation("Please, press a button!");
  });
}

function confirmOperation(message) {
  var txt;
  if (message == true) {
    txt = "You pressed OK!";
    document.getElementById("demo").innerHTML = txt;
    return true;
  } else {
    txt = "You pressed Cancel!";
    document.getElementById("demo").innerHTML = txt;
    //setTimeout(confirmOperation, 0, "Please, press a button!");
    return false;
  }
}

</script>

我希望有所帮助。