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

356
Visualizações
I want the images not to be repeated, just to change the order randomly

I have this code from codepen, but when loading the images it repeats them, and what I want to do is keep them appearing randomly, but not repeat them.

HTML:

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>CodePen - Random image grid</title>
  <link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->

<!-- partial -->
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script><script  src="./script.js"></script>

</body>
</html>

JS:

document.addEventListener('DOMContentLoaded', function() {
    for (i=1; i<8; i++){    
        (function(i){
            setTimeout(function () {
                $('<img class="sq" src="ads/ads-' + Math.floor((Math.random() * 7)+1) + '.jpg">').appendTo('body');
            }, i * 1);
        }(i));
    };
}, false);

Any idea how I can do it, I'm kind of new to js, ​​I'm just learning

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

0

Instead of generating random numbers in each iteration, generate the array of possible numbers (0..7), shuffle them, and then use that shuffled array to produce the images.

Side node: as you use jQuery, use it with its full potential:

function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

$(function() {
    let nums = shuffle([...Array(8).keys()]);
    
    (function loop() {
        if (!nums.length) return;
        let i = nums.pop() + 1;
        $("<img>", {
            class: "sq",
            src: `ads/ads-${i}.jpg`,
            alt: i
        }).appendTo("body");
        setTimeout(loop, 100);
    })();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório

0

You could create an array with all the images you want to add. Then while there is at least one image, you add it to the screen and remove it from the array at a given interval.

 document.addEventListener(

  "DOMContentLoaded",
  function () {
    const imgs = [];

    for (let i = 1; i < 8; i++) {
      imgs.push(`ads/ads-${i}.jpg`);
    }

    const intervalID = setInterval(() => {
      while (imgs.length > 0) {
        const img = imgs[Math.floor(Math.random() * imgs.length)];

      $(
        `<img class="sq" src="${img}">`
      ).appendTo("body");

        imgs.splice(imgs.indexOf(img), 1);
      }

      clearInterval(intervalID);
    }, 100);
  },
  false
);
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