Случайный выбор цикла JavaScript из массива

1

У меня проблема с этим. Я хочу выбирать случайное слово из массива каждый раз при загрузке всплывающих окон. Но слово не меняется. Я всегда получаю результаты как:

(march, march, march.. january, january, january, january, january)...

Он просто выбирает случайный месяц, а затем использует его в каждом цикле. Я хочу сделать его случайным каждый цикл. Может кто-нибудь, пожалуйста, помогите мне?

var i;

for (i = 0; i < 5; i++) {
  $("#notification").fadeIn("slow").delay(1000).fadeOut("slow");

  var myArray = ['January', 'February', 'March'];
  var rand = myArray[Math.floor(Math.random() * myArray.length)];

  document.getElementById("notification").innerHTML = rand;
}

//$("#notification").append(rand);
#notification {
  position: fixed;
  bottom: 5px;
  left: 5px;
  width: 170px;
  /* set to 100% if space is available */
  height: 70px;
  z-index: 105;
  text-align: center;
  font-weight: normal;
  font-size: 12px;
  color: white;
  background-color: #FF7800;
  box-shadow: 0 0 10px #222;
  padding: 5px;
  opacity: 0.7;
  filter: alpha(opacity=70);
  /* For IE8 and earlier */
}

#notification span.dismiss {
  border: 2px solid #FFF;
  padding: 0 5px;
  cursor: pointer;
  float: right;
  margin-right: 10px;
}

#notification a {
  color: white;
  text-decoration: none;
  font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification" style="display: none;">
  <span class="dismiss"><a title="dismiss this notification">X</a></span>
</div>

Ссылка JSfiddle

  • 2
    Вы не должны выполнять асинхронные операции (показывать / скрывать элемент с анимацией) в синхронном цикле. Это приведет к нежелательному поведению.
  • 0
    так что мне делать? я в отчаянии, правда
Теги:
arrays
loops

2 ответа

2

Цикл for завершается непосредственно перед началом анимации, поэтому вы видите только последнее генерируемое случайное значение.

Вместо этого вам нужно каждый раз ждать, пока анимация завершится до следующей итерации. Это можно сделать с аргументом обратного вызова для fadeOut:

var myArray = ['January', 'February', 'March']; 
(function loop(i) { 
   if (i >= 5) return; // all iterations have been completed
   var rand = myArray[Math.floor(Math.random() * myArray.length)];
   document.getElementById("notification").textContent = rand;
   // Use callback argument of fadeOut to chain to next iteration
   //    when the animation is complete
   $("#notification").fadeIn("slow").delay(1000).fadeOut("slow", loop.bind(null, i+1));
})(0); // Execute the loop function immediately with i = 0
#notification {
    position: fixed;
    bottom: 5px;
    left: 5px;
    width:170px; /* set to 100% if space is available */
    height: 70px;
    z-index:105;
    text-align:center;
    font-weight:normal;
    font-size:12px;
    color:white;
    background-color:#FF7800;
    box-shadow:0 0 10px #222;
    padding:5px;
    opacity: 0.7;
    filter: alpha(opacity=70); /* For IE8 and earlier */
}
#notification span.dismiss {
    border:2px solid #FFF;
    padding:0 5px;
    cursor:pointer;
    float:right;
    margin-right:10px;
}
#notification a {
    color:white;
    text-decoration:none;
    font-weight:bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification" style="display: none;">
  <span class="dismiss"><a title="dismiss this notification">X</a></span>
</div>
  • 0
    большое спасибо!
  • 0
    Пожалуйста ;-)
0

Вы добавляете задержку для анимации через циклы.

Однако всякое случайное значение рассчитывается при первом тике.

var i;
var myArray = ['January', 'February', 'March','April','May']; 
for (i = 0; i < 5; i++) { 
$("#notification").fadeIn("slow").delay(1000).fadeOut("slow");

setTimeout(function(){
var rand = myArray[Math.floor(Math.random() * myArray.length)];
  document.getElementById("notification").innerHTML = rand;
  // slow refer to 600ms, 600*2+1000 = 2200
  },2200*i);
}

http://jsfiddle.net/vmsb14dL/81/

Ещё вопросы

Сообщество Overcoder
Наверх
Меню