Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!