简体   繁体   English

如何制作间隔计时器?

[英]How can I make an interval timer?

I have the bootstrap loading bar: 我有引导加载栏:

  <div class="progress">
  <div class="progress-bar progress-bar-success progress-bar-striped active" id="loading" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
  </div>
  </div>

I'm trying to change the width of the bar every few seconds so it looks like the bar is making progress. 我正在尝试每隔几秒钟更改一次条的宽度,以便看起来条正在取得进展。

I have this but it's not working: 我有这个,但是不起作用:

   setInterval(function () {
      var percentl = percentl + 5;
      document.getElementById("loading").style.width = percentl + "%";
  }, 1000);

You're declaring var percentl in the function block, so percentl is declared in the scope of the internal function only, each time the function is invoked the value of percentl is undefined and after setted to NaN (as RobG says in the comment). 你声明var percentl功能块,所以percentl在内部功能的范围内声明的唯一,每个函数被调用的值时percentl是不确定的,并设置好的为NaN后(如RobG在注释中说的)。 Try this: 尝试这个:

var percentl = 0;
setInterval(function () {
  percentl = percentl + 5;
  document.getElementById("loading").style.width = percentl + "%";
}, 1000);

1) percentl has a local scope in your function. 1)percentl在您的函数中具有局部作用域。 You are redefininng it to the same value every time it is called. 每次调用时,您都将其重新定义为相同的值。

set percentl with a global scope that can be accessed by your anonymous function every time it is called. 将percentl设置为全局范围,每次调用匿名函数都可以访问它。

2) You are also calling setInterval only once. 2)您也只调用一次setInterval。 You should call it in a loop until you reach 100%. 您应该循环调用它,直到达到100%。 Something like: 就像是:

var percentl = 0;


function increase(){

setInterval(function () {
      percentl = percentl + 5;
      document.getElementById("loading").style.width = percentl + "%";
      if(percentl < 100){
        increase();
      }
  }, 1000);
}
var i = 0;
function increase(){
    setInterval(function () {
        document.getElementById("loading").style.width = i + "%";
        i++;
        increase();
    }, 1000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM