使用最小值和最大值随机化setInterval

时间:2018-01-17 10:19:48

标签: javascript jquery

我有以下代码:

var myVar;    
function showDiv() {
  var random = Math.floor(Math.random() * $('.notification').length);
  $('.notification').eq(random).fadeIn(200).delay(3000).fadeOut(200);
}
function stopFunction() {
    clearInterval(myVar);  // stop the timer
}
$(document).ready(function () {
    myVar = setInterval(showDiv, 2000);
});

我现在尝试的是,随机化setInterval但是在最小2000和最大10000的范围内。

这是我的小提琴:https://jsfiddle.net/gkq21ppt/

2 个答案:

答案 0 :(得分:3)

您需要使用setTimeout以{2000}之间的随机值作为时间间隔来调用showDiv。这可以在createRandomInterval函数中完成,以便您可以在showDiv函数中重复使用它,以便在下一次随机时间间隔之后执行它。

样品:



var myVar;    
function showDiv(){
  var random = Math.floor(Math.random() * $('.notification').length);
  $('.notification').eq(random).fadeIn(200).delay(3000).fadeOut(200);
  createRandomInterval();
}

function createRandomInterval(){
  setTimeout(showDiv, 2000+ Math.random() * 8000);
}
$(document).ready(function(){
    createRandomInterval();
});

.notification {
  width: 200px;
  height: 50px;
  background-color: yellow;
  border: 1px solid rgba(0,0,0,0.2);
  margin-bottom: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  display: none;/* hide initially so that fadIn() fadeOut() will work
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first" class="notification">first</div>
<div id="second" class="notification">second</div>
<div id="third" class="notification">third</div>
<div id="fouth" class="notification">fourth</div>
<div id="fifth" class="notification">fifth</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您无法更改setInterval功能的间隔,以下是使用setTimeout实现此目的的方法。 (注意:我已经删除了你的3000ms延迟)

var myVar;    
function showDiv(){
  var random = Math.floor(Math.random() * $('.notification').length);
  $('.notification').eq(random).fadeIn(200);
  setTimeout(function () {
      $('.notification').eq(random).fadeOut(200);
      setTimeout( showDiv, 300);
  }, 2000 + Math.random() * 8000);
}

$(document).ready(function(){
    showDiv();
});

PS:updated fiddle here