Javascript 进度条无法正确加载

Javascript Progess bar wont load correctly

我正在开发一个简单的 jquery 加载栏,我可以 post 达到。我的问题是,即使在 javascript.

中设置了 settimeout,它似乎也只能跳转到最后一个结果

测试脚本包括 3 个按钮,效果很好,但是我需要能够从底部的内联代码调用函数。这似乎跳到最后的结果 75% 而没有显示 25% 并等待 3 秒,正如我所希望的那样。

<!DOCTYPE html>
<html>
<style>
#Progress {
  width: 100%;
  background-color: #ddd;
}

#Bar {
  width: 1%;
  height: 30px;
  background-color: #4CAF50;
}
</style>
<body>

<h1>Progress Bar</h1>

<div id="Progress">
  <div id="Bar" style="width:0px;"></div>
</div>

<br>
Buttons for testing bar not needed in actual script<br>
<button onclick="move(50)">Test Bar 50%</button> <br>
<button onclick="move(75)">Test Bar 75%</button> <br>
<button onclick="move(100)">Test Bar 100%</button> <br>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
function move(amount) {
  var elem = document.getElementById("Bar");   
  elem.style.width = amount + '%'; 
}
// Inline calls I need to use for my script. These seem to jump to the last one when loaded dispite timeout.
setTimeout(function(){
  move(25);
}, 3000);
setTimeout(function(){
  move(75);
}, 3000);
</script>

</body>
</html>

目前,两个 setTimeout 并行调用 运行,所以完成后您只能看到 75% 的结果(即使发生了 25% 的结果,它也不再可见)。

您可以嵌套 setTimeout 调用,以便它们按顺序执行。请参阅下面的代码段:

function move(amount) {
  var elem = document.getElementById("Bar");
  elem.style.width = amount + '%';
}
// nest the setTimeout calls so they fire sequentially
setTimeout(function() {
  move(25);
  setTimeout(function() {
    move(75);
  }, 3000);
}, 3000);
#Progress {
  width: 100%;
  background-color: #ddd;
}

#Bar {
  width: 1%;
  height: 30px;
  background-color: #4CAF50;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Progress">
  <div id="Bar" style="width:0px;"></div>
</div>

<br> Buttons for testing bar not needed in actual script<br>
<button onclick="move(50)">Test Bar 50%</button> <br>
<button onclick="move(75)">Test Bar 75%</button> <br>
<button onclick="move(100)">Test Bar 100%</button> <br>

更新

如果要显示的进度点数量可变,则可以使用以下改编自此 useful answer 的技术。

function move(amount) {
  var elem = document.getElementById("Bar");
  elem.style.width = amount + '%';
}

// set array of points:
var movements = [10, 20, 30, 50, 75, 99, 100];
var i = -1;

function moveSequence() {
  move(movements[i++]);
  if (i < movements.length) setTimeout(moveSequence, 1000);
}
moveSequence();
#Progress {
  width: 100%;
  background-color: #ddd;
}

#Bar {
  width: 1%;
  height: 30px;
  background-color: #4CAF50;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Progress">
  <div id="Bar" style="width:0px;"></div>
</div>

<br> Buttons for testing bar not needed in actual script<br>
<button onclick="move(50)">Test Bar 50%</button> <br>
<button onclick="move(75)">Test Bar 75%</button> <br>
<button onclick="move(100)">Test Bar 100%</button> <br>