【问题标题】:JavaScript functions not executed in the right order with sleep睡眠时 JavaScript 函数未按正确顺序执行
【发布时间】:2017-10-12 14:27:25
【问题描述】:

我想隐藏一个元素,一秒后显示一个新元素,

这是简化的代码:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}



function loadNewSubmenu()
{
    document.getElementById("content-1").className = "hide-part";
    sleep(1000);
    document.getElementById("content-2").className = "show-part";
}
.hide-part{
  display : none;
}
<button id="content-1" class="show-part">B1</button>
<button id="content-2" class="hide-part">B2</button>
<button onclick="loadNewSubmenu()">click me</button>

我的预期:

  • 隐藏元素#content-1
  • 等待一秒钟
  • 显示元素#content-2

但这就是我得到的:

  • 一秒等待
  • 元素 #content-1 已更改
  • 元素#content-2已更改

我知道我可以使用setTimeout 来修复它,但是这种行为背后的原因是什么?

【问题讨论】:

标签: javascript html


【解决方案1】:

只需使用setTimeout()

function loadNewSubmenu() {
  document.getElementById("content-1").className = "hide-part";
  setTimeout(function() {
    document.getElementById("content-2").className = "show-part";
  }, 1000)
}
.hide-part {
  display: none;
}
<button id="content-1" class="show-part">B1</button>
<button id="content-2" class="hide-part">B2</button>
<button id="content-1" onclick="loadNewSubmenu()">click me</button>

【讨论】:

    【解决方案2】:

    你可以使用setTimeout();这是一个例子:`

    <script>
        function loadNewSubmenu()
            {
                document.getElementById("content-1").className = "hide-part";
    
                setTimeout(function(){
                    document.getElementById("content-2").className = "show-part";
                },1000);
            }
    </script>`
    

    【讨论】:

      【解决方案3】:

      使用 setTimeout 而不是 sleep

      function loadNewSubmenu()
      {
          document.getElementById("content-1").className = "hide-part";
          setTimeout(function(){  document.getElementById("content-2").className = "show-part"; },1000);
         
      }
      .hide-part{
        display : none;
      }
      <button id="content-1" class="show-part">B1</button>
      <button id="content-2" class="hide-part">B2</button>
      <button id="content-3" onclick="loadNewSubmenu()">click me</button>

      【讨论】:

        猜你喜欢
        • 2019-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-08
        • 1970-01-01
        • 2013-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多