设置间隔随机+超时

时间:2017-04-03 12:10:26

标签: javascript jquery random timeout setinterval

我试图在我的页面上显示“等待”,然后“等待等待”,然后“等待等待”等直到~100次,我希望添加“等待”之间的时间是随机,到目前为止,我已经设法显示等待到100,但我不能添加间隔的随机..(现在我放10,以便它快速结束)。

我已经找到了关于这些主题的答案,但我似乎无法将它们整合到我的代码中。

setInterval + Random Number setInterval + Random Number

 var timesRun = 0;
        var t = "wait";
        var interval = setInterval(function(){
            timesRun += 1;
            if(timesRun === 10){
              t = t + "...";
              document.getElementById("sample2-progress").innerHTML = t;
              clearInterval(interval);
            }

            document.getElementById("sample2-progress").innerHTML = t;
             t = t + " wait";
            

        }, 200); 
#preloader  {
     position: fixed;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
     background-color: #000;
     z-index: 99999;
    height: 100%;
    overflow: hidden;
 }

#status  {
     width: 100%;
     height: 100%;
     position: absolute;
     left: 0%;
     color: white;
     top: 0%;
     background-repeat: no-repeat;
     background-position: center;
     /*margin: -50% 0 0 -50%;*/
     text-align: center;
 }

 #sample2-log{
 	display: none;
 }

 #sample2-progress{
 	font-size: 6vh;
top: 2vw;
position: fixed;
text-align: center;
width: 98vw;
left: 2vw;
text-align:left;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <div id="preloader">

    <div id="status">
      <textarea id="sample2-log"></textarea>
      <div id="sample2-progress" class="progress"></div>
    </div>

  </div>

1 个答案:

答案 0 :(得分:1)

根据我的理解,由于每次运行都需要不同的间隔,因此最好使用setTimeout

注意:出于演示目的,我将延迟范围保持在10秒之内。您可以在控制台中查看延迟值。

示例代码

&#13;
&#13;
var timesRun = 0;
var t = "wait ";

function initTimeout() {
  var delay = Math.floor(Math.random() * 1000000) % 10000;
  console.log(delay)
  setTimeout(function() {
    var str = "...";
    if (++timesRun < 10) {
      str = t
      initTimeout();
    }
    notify(str);
  }, delay);
}

function notify(str) {  
  document.getElementById("sample2-progress").innerHTML += str;
}
initTimeout();
&#13;
#preloader {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
  z-index: 99999;
  height: 100%;
  overflow: hidden;
}

#status {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0%;
  color: white;
  top: 0%;
  background-repeat: no-repeat;
  background-position: center;
  /*margin: -50% 0 0 -50%;*/
  text-align: center;
}

#sample2-log {
  display: none;
}

#sample2-progress {
  font-size: 6vh;
  top: 2vw;
  position: fixed;
  text-align: center;
  width: 98vw;
  left: 2vw;
  text-align: left;
}
&#13;
<div id="preloader">
  <div id="status">
    <textarea id="sample2-log"></textarea>
    <div id="sample2-progress" class="progress"></div>
  </div>
</div>
&#13;
&#13;
&#13;