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

253
Visualizações
Can't use variable as setInterval delay?

Instead of having a set amount of time between the loops, I need the delay to be dynamic. But when using a variable it loops like it has no delay at all.

(I am using the p5 and p5.sound libraries)

I'm trying to have the delay between loops be the length of a randomly picked song. So I'm setting the value of the delay in the setInterval loop to a variable which is the length of the song.

This works perfectly as I expected, and loops every second. But it's not what I want.

    let e;
    setInterval(()=>{
        const r = floor(random(26));
        music[r].play();
        music[r].rate(20);
        music[r].setVolume(0.0125);    
    
        background(0, 255, 0);
        text(musicList[r], 0, height);
        e = floor(music[r].duration() * 1000);
    }, 1000);

This doesn't work as I expected, and just loops like it's a while loop.

    let e;
    setInterval(()=>{
        const r = floor(random(26));
        music[r].play();
        music[r].rate(20);
        music[r].setVolume(0.0125);  
      
        background(0, 255, 0);
        text(musicList[r], 0, height);
        e = floor(music[r].duration() * 1000);
    }, e);

Question is, can't I use a variable as the value of delay needed in the setInterval loop? Am I doing something wrong? Or am I missing something?

If what I'm trying to do just doesn't work at all, what other options for loops with a dynamic delay can I use?

I am still very much a rookie at programming so please excuse any rookie mistakes.

about 4 years ago · Juan Pablo Isaza
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