0

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.

keppy
  • 21
  • 2
  • You've to define `e` outside of the callback function. Currently the variable has no value when it is used. – Teemu Mar 26 '22 at 08:15
  • Even after defining `e` with let's say `1000`, the song starts playing after 1 second, then I'm redefining `e` to a different value, but it still keeps looping indefinitely every 1 seconds. `e` for whatever reason doesn't want to change value :/ – keppy Mar 26 '22 at 08:25
  • Yes, that's the expected behavior. You're calling `setInterval` only once, and the delay is also defined only once. If you need a varying interval, use nested [timeouts](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) instead of `setInterval`. – Teemu Mar 26 '22 at 08:27
  • So the `setInterval` delay value can't be changed unless it's called again with a different value? In which case it indeed makes more sense to just use nested timeouts then. Thanks! – keppy Mar 26 '22 at 08:34
  • Somewhat, yes. What you linked and what Teemu just told me both come down to using `setTimeout` instead of using `setInterval`. Thanks though! – keppy Mar 26 '22 at 08:44

0 Answers0