循环使用 setInterval (jQuery ) 的函数

Loop over a function that uses setInterval (jQuery )

我要显示和隐藏进度条 10 次。这就是我使用 for 循环的原因,我在其中调用函数 oneLoop。 oneLoop 每 100 秒调用一次帧函数。 Frame 函数用于改变进度条。

然而,for循环只执行一次。我不想使用另一个 setInterval 函数来执行 oneloop 函数,因为在间隔期间可能会发生不同步事件,然后事情变得非常糟糕。我怎样才能实现执行 oneLoop 10 次并且每次执行都在前一个循环结束后开始?

代码:

for(var i=0;i<10;i++){
    $(".progress").show();
  var w = {j:100};
  oneLoop(w);
}

function oneLoop(w){

  timerId = setInterval(function(){
    frame(w)
  },100);
}

function frame(w) {
  //when the percentage becomes zero, the progress bar closes 
  if (w.j === 0) {
    clearInterval(timerId);
    $(".progress").fadeOut(); 
  }
  //the percentage is descreased be 1%
  else {
    w.j = w.j - 1;
    $(".progress-bar").width(w.j + '%'); 
  }
}

和HTML:

<div class="progress">
  <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">
  </div>
</div>

https://jsfiddle.net/DTcHh/27828/

不需要 for 循环 :

let progress=$(".progress");
let progressBar=$(".progress>.progress-bar");
let count=0;
let maxCount=10;
function run(){
  progressBar.width('100%'); 
  progress.fadeIn(400,()=>{
   let w={j:100};
    let timerId=setInterval(()=>{
      if (w.j === 0) {
        count++;
        clearInterval(timerId);
        progress.fadeOut(400,()=>{
        if(count<maxCount)
          run();
        else
          console.log("ended")
        });
      }
      else {
        w.j = w.j - 1;
        progressBar.width(w.j + '%'); 
      }
    },100);
  });
}
run();
.progress{
  width:100px;
  height:20px;
  background-color:blue;
}
.progress-bar{
  background-color:red;
  height:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress">
  <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">
  </div>
</div>

试试这个...

var p = 100;
var timerId;
function oneLoop() {
  timerId = setInterval(function() {
    p -= 1;
    frame();
  }, 100);
}
function frame() {
  if (p === 0) {
    $(".progress").fadeOut();
    clearInterval(timerId);
  } else {
    $(".progress-bar").width(p + '%');
  }
}
oneLoop();
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress">
  <div class="progress-bar progress-bar-success" style="width: 100%" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">
  </div>
</div>