循环使用setInterval(jQuery)的函数

时间:2016-12-12 11:01:32

标签: javascript jquery html progress-bar setinterval

我想要显示并隐藏进度条10次。这就是为什么我使用for循环,我在其中调用函数oneLoop。 oneLoop每100秒调用一次帧功能。框架功能用于更改进度条。

但是,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/

2 个答案:

答案 0 :(得分:2)

无需for循环:

&#13;
&#13;
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();
&#13;
.progress{
  width:100px;
  height:20px;
  background-color:blue;
}
.progress-bar{
  background-color:red;
  height:100%;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个......

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>