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

332
Visualizações
Javascript how to display random users every nth second?

I've created a function that reads a 8 random usernames from an API website using fetch

fetch('https://api.github.com/users').then(function(response) {
  response.json().then(function(users){
    document.write("Highlighred Github users")
    for (let i=0; i< 8; i++) {
      document.write('<br>')
      document.write((users[Math.floor(Math.random() *users.length)].login))
    }
  });
}).catch(err => console.error(err));

I'm trying to modify it such that the 8 random users being displayed change/update every 30 seconds with a new list. I've attempted to do such a thing through modifying the for loop to be a function that operates based on a timer. The following replaces the for loop code in the above

var myVar=setInterval(function(){myTimer()},30000);
function myTimer() {
  for (let i=0; i< 8; i++) {
    document.write('<br>')
    document.write((users[Math.floor(Math.random() *users.length)].login))
  }

However, this function is generating a new list of 8 random users every nth second rather than changing the existing one

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

0

You can not use document.write after the page loads. Add an element to the page. Set the text of that element.

const users = [
  { login: 'A' },
  { login: 'B' },
  { login: 'C' },
  { login: 'D' },
];

const elem = document.getElementById("user");

function showNext() {
  user.textContent = users[Math.floor(Math.random() * users.length)].login
  window.setTimeout(showNext, 3000);
}

showNext();
<div id="user"></div>

Better solution is using a shuffle so you do not repeat. And when you run out, you can either stop or reshuffle

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;
}

const users = [
  { login: 'A' },
  { login: 'B' },
  { login: 'C' },
  { login: 'D' },
];

const elem = document.getElementById("user");

function runNames() {
  const shuffled = shuffle(users.slice());
  function showNext() {
    user.textContent = shuffled.pop().login;
    const runNext = shuffled.length ? showNext : runNames;
    window.setTimeout(runNext, 3000);
  }
  showNext();
}

runNames();
<div id="user"></div>

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