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

119
Visualizações
log a nested loop element every second for at least a minute? in Javascript?
let innerArrayOne = [1,"red","fed"]

let innerArrayTwo = [2,"blue","you"]

let innerArrayThree = [3,"green","bean"]

let innerArrayFour = [4,"yellow","fellow"]

let arrayS = [innerArrayOne,innerArrayTwo,innerArrayThree, innerArrayFour]

Here is what I have tried so far

for(let i = 0; i < arrayOfDoom.length; i++){
      console.log("----")
      console.log(arrayOfDoom[i])
      console.log("----")
      for(let j = 0; j < arrayOfDoom[i].length;j++)
      console.log(arrayOfDoom[i][j])
    }
}

Here is the test data I've made. Here is what I have tried so far. That gives you each element in the array.


function loop(count, callback, done) {
  let counterForLoop = 0;


  
  let next = function () {setTimeout(iteration, 500);};
  
  let iteration = function () {
      if (counterForLoop < count) { callback(counterForLoop, next);
      } else { done && done();}
   
      counterForLoop++; 

    }
  iteration();
}

loop(10000, function (i, next) {next();})


loop(9, function (i, nextI) {
  console.log("----")
  console.log(i)
  console.log("----")
  loop(3, function (j, nextJ) {
  console.log(arrayS[i][j]);nextJ();
}, nextI);});

This is from the only other close StackOverflow I checked. It works, but it ends after the final element in the first array. I don't entirely understand recursion, so every time I have tried to edit, like setting the counter to zero after it hits 8, it breaks it. I would like the output to be

1 
red 
fed
2
blue
you
....

With one element coming out, every second for one to two minutes, and the loop once it hits the end, it just needs to repeat.

Any ideas or what should I research?

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

0

Future homies should also consider breaking the problem in two: (1) doing anything on an interval for a fixed time, and (2) logging randomly.

A little dressing-up of setInterval can provide can hide the time math and stop after some specified elapsed time.

Logging randomly can be improved, too, by shuffling, then logging sequentially, in order to get randomness without repetition.

let innerArrayOne = [1,"red","fed"];
let innerArrayTwo = [2,"blue","you"];
let innerArrayThree = [3,"green","bean"];
let innerArrayFour = [4,"yellow","fellow"];
let arrayS = [innerArrayOne,innerArrayTwo,innerArrayThree, innerArrayFour];

// fisher-yates shuffle, thanks to https://stackoverflow.com/a/2450976/294949
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;
}

// invoke fn on a set interval until elapsed ms have elapsed
function repeat(fn, interval, elapsed) {
  fn() // up to author if we start right away
  const start = (new Date()).getTime(); // ms since epoch
  const id = setInterval(() => {
    const now = (new Date()).getTime();
    if (now - start > elapsed) {
      clearInterval(id);
    } else {
      fn()
    }
  }, interval);
}

let shuffledArray = shuffle(arrayS.slice());
let index = 0;

repeat(() => {
  console.log(shuffledArray[index])
  if (index < shuffledArray.length-1) index++;
  else {
    shuffledArray = shuffle(arrayS.slice());
    index = 0;
  }
}, 800, 4800)

about 4 years ago · Juan Pablo Isaza Relatório

0

For all the future homies, this is how I got it working

function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}


let i = 0;
let loopCounter = 0;
let randomNumber = 1

const outerLoop = () => {
    for (i; i < arrayS.length;){
      console.log(randomNumber);
      console.log(arrayS[randomNumber][loopCounter])
      i++;
      loopCounter++;
      if(loopCounter === 3){
        loopCounter = 0
        randomNumber = getRandomInt(8)
        
      }
      if(i === 4){
        i = 0
      }
      break;
        }
}
setInterval(outerLoop, 2000);
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