Referee Andy
Referee Andy

Reputation: 115

Randomize setInterval with minimum and maximum

I have the following code:

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);
});

What I try now is, to randomize setInterval but in a range of min 2000 and max 10000.

Here is my fiddle: https://jsfiddle.net/gkq21ppt/

Upvotes: 1

Views: 246

Answers (2)

surajck
surajck

Reputation: 1175

You cannot change the interval of a setInterval function, here is how you can achieve this using setTimeout. (Note: I have removed your 3000ms delay)

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

Upvotes: 1

Chirag Ravindra
Chirag Ravindra

Reputation: 4830

You will need to use setTimeout to call showDiv with random values between 2000 and 10000 as the time interval. This can be done in createRandomInterval function so that you can reuse it in showDiv function so that it will be executed after a random time interval the next time.

Sample:

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>

Upvotes: 3

Related Questions