Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
Fade elements in/out in sequence

I created an array that stores the ids of buttons. Button ids are #red, #green, #blue and #yellow

I created another function the randomly selects a color and stores it inside of another array.

I am tying to iterate the second array using a for loop and use a fade in/out effect on the buttons so the outcome will be an ordered fade in and out effect.

For example:

array = ['red','green','blue'];

First the red button fades in and out then the green and lastly the blue.

The outcome I get is a fade in and out effect almost at the same time. Can anybody please provide a solution and tell me why it happens?

var buttonColours = ["red", "blue", "green", "yellow"];
var GamePattern = [];

function nextSequence() {
  var randomNumber = Math.floor((Math.random() * 4));
  var randomChosenColour = buttonColours[randomNumber]
  GamePattern.push(randomChosenColour);
}

function playSequence(sequence) {
  for (var i = 0; i < sequence.length; i++) {
    $("#" + sequence[i]).fadeOut(1000).fadeIn(1000)
  }
}

nextSequence()
nextSequence()
nextSequence()
playSequence(GamePattern)
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
  <div lass="row">
    <div type="button" id="green" class="btn green"></div>
    <div type="button" id="red" class="btn red"></div>
  </div>
  <div class="row">
    <div type="button" id="yellow" class="btn yellow"></div>
    <div type="button" id="blue" class="btn blue"></div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The issue with your code is because you run all the fade effects at the same itme.

You can simplify the approach and the code by randomising the order of your input array and then iterating through it to fade in/out the relevant elements, adding an incremental delay to each so that only one fade happens at a time in sequence. Try this:

// shuffle logic credit: https://stackoverflow.com/a/2450976/519413 @coolaj86
function shuffle(array) {
  let currentIndex = array.length,  randomIndex;
  while (currentIndex != 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
  }
  return array;
}

var buttonColours = ["red", "blue", "green", "yellow"];
shuffle(buttonColours).forEach((id, i) => {
  $('#' + id).delay(i * 2000).fadeOut(1000).fadeIn(1000);
});
.container .row {
  display: inline-block;
}
.container .row .btn {
  width: 100px;
  height: 100px;
  display: inline-block;
}

.btn.green { background-color: #0C0; }
.btn.red { background-color: #C00; }
.btn.yellow { background-color: #CC0; }
.btn.blue { background-color: #00C; }
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
  <div class="row">
    <div type="button" id="green" class="btn green"></div>
    <div type="button" id="red" class="btn red"></div>
  </div>
  <div class="row">
    <div type="button" id="yellow" class="btn yellow"></div>
    <div type="button" id="blue" class="btn blue"></div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório

0

Javascript is by default asynchronous - meaning it won't wait for the fade in/out unless you explicitly tell it to do so.

I'd advise using a simple setTimeout command, see here for more information and alternatives

For example, if you change this part:

for (var i=0 ; i<sequence.length ; i++){
    $("#" + sequence[i]).fadeOut(1000).fadeIn(1000)
}

To this:

for (var i=0 ; i<sequence.length ; i++){
    setTimeout(function() {
         $("#" + sequence[i]).fadeOut(1000).fadeIn(1000)
    }, 2000)
}

It will wait 2000 miliseconds before going to the next point in the loop

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda