Nate Rice Nate Rice - 1 year ago 75
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 id="div" onclick="hide()" style="visibility:hidden;">Doge</div>


<script type = "text/javascript">

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

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


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

Answer Source

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(){ = "hidden";

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

function showIn(delay) {
  setTimeout(function() { = "visible";
  }, delay);

// call directly in the beginning to show the div
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download