Javascript按时间加载吧

时间:2017-01-26 13:10:12

标签: javascript

我搜索了这么多,但我无法弄清楚如何配置我的酒吧。

我计划放置3个按时间自动执行的加载条:

used

我的代码是这样的(请注意,我不知道如何更改此值,我尝试但无法正常工作......这是我需要的帮助,框架内容)

1st will start from 30 to 60 seconds
2nd from 300 to 1800 seconds
3rd from 1801 to 1860 seconds

谢谢大家

2 个答案:

答案 0 :(得分:5)



startBar(3000,4000 ,"my1Bar");
startBar(4001,20000 ,"my2Bar");
startBar(20001,22000,"my3Bar");

function startBar(start_ms,end_ms,id){
    return setTimeout(function(){
        loadBar(start_ms,end_ms,id);
    }, start_ms);
}
function loadBar(start_ms,end_ms,id){
    var elem = document.getElementById(id); 
    var widthAtStart = 0;
    var widthAtEnd = 100;
    var timeDuration=end_ms-start_ms;
    var remindWidth=widthAtEnd-widthAtStart;
    var curWidth=widthAtStart;
    var lastTime=Date.now();
    var intervalId = setInterval(frame, 10);
    function frame() {
        var dt=Date.now()-lastTime;
        lastTime=Date.now();
        var w=remindWidth*dt/timeDuration;
        if (curWidth >= widthAtEnd) {
            clearInterval(intervalId);
            elem.style.width = '100%'; 
        } else {
            curWidth+=w;
            elem.style.width = curWidth + '%'; 
        }
    }
}

.bars>div{
  position:relative;
  width:100%;
  height:22px;
  padding:1px;
  margin:2px;
  background:#ccc;
}
.bars>div>div{
  position:absolute;
  height:20px;
  width:0;
  background:red
}

<div class="bars">
  <div><div id="my1Bar"></div></div>
  <div><div id="my2Bar"></div></div>
  <div><div id="my3Bar"></div></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是您的代码的一个重构版本。要运行进度条,您需要在您希望它开始和结束的时间以及进度条元素的startBar()调用id函数。例如,在下面的代码中,第一个栏将在1秒后开始,在6秒后结束(总共运行5秒)。

我还使用了HTML5 progress元素。它比使用div更好,因为progress是语义的,你不必操纵任何css参数,你只需改变它的值。此外,它还具有本机平台和浏览器呈现的优势。但是,如果你想在所有平台上将它设置为相同的样式,那可能会有点痛苦。这是styling guide for progress element

startBar(1, 6, "first");
startBar(3, 6, "second");
startBar(5, 8, "third");

function startBar(from, to, id) {
  // Convert seconds to miliseconds
  from *= 1000;
  to *= 1000;

  // Delay the start of the loop for 'from' seconds
  setTimeout(function() {
    var bar = document.getElementById(id);
    var duration = to - from;
    var start = Date.now();

    // Start the loop
    var loop = setInterval(function() {
      var runningFor = Date.now() - start;
      if (runningFor <= duration) {
        bar.value = Math.ceil(runningFor / duration * 100);
      } else {
        bar.value = 100;
        clearInterval(loop);
      }
    }, 10);
  }, from);
}
progress {
  width: 100%;
}
<progress id="first" value="0" max="100"></progress>
<progress id="second" value="0" max="100"></progress>
<progress id="third" value="0" max="100"></progress>