Nate Rice Nate Rice - 11 days ago 5
HTML Question

Set an array to select different variables onclick

I have a little experimental setup that I am editing to create a div that appears at random times and when you click it goes away. I am having issues forcing the variable "x" to be a different number from the array everytime you click it. Instead it will pick one number from the array at the start and stick with it the entire time.

DIV:

<div id="div" onclick="hide()" style="visibility:hidden;">Doge</div>


JS:

<script type = "text/javascript">

var interval = [5000, 1000, 10000, 6000, 500];
var x = interval[Math.floor(Math.random() * interval.length)];
setInterval(function(){
document.getElementById('div').style.visibility = "visible";
},x);

function hide(){
document.getElementById('div').style.visibility = "hidden";
var x = interval[Math.floor(Math.random() * interval.length)];
}

</script>


Every time you click the div I want it to reappear at a different time interval.

Answer

setInterval takes a delay value and uses that for every interval. It is not affected by you updating the variable. What you want is setTimeout, which you will set every time that your hide function is called.

var interval = [5000, 1000, 10000, 6000, 500];
var div = document.getElementById('div');

function hide(){
  div.style.visibility = "hidden";
  showIn(randomInterval());
}

function randomInterval() {
  return interval[Math.floor(Math.random() * interval.length)];
}

function showIn(delay) {
  setTimeout(function() {
    div.style.visibility = "visible";
  }, delay);
}

// call directly in the beginning to show the div
showIn(randomInterval());