1

I have a for loop to play sounds. I want to break it when clicking on a button. I'm not sure if I'm facing issues with async, rerendering ... but it doesn't work. Any ideas?

const onStart = async() => {
  for (const el of playlist) {
    if (breakLoop) {
      break;
    }

    await play(el);

    if (breakLoop) {
      break;
    }
  }
}

const onStop = () => {
  setBreakLoop((prev) => true);
}
ggorlen
  • 44,755
  • 7
  • 76
  • 106
rodbs
  • 185
  • 1
  • 4
  • 12

1 Answers1

1

I don't have enough context to give an exact answer, but if I were to think about a similar situation, I'd go about it like this:

// a play function to simulate something that takes some time
const play = (el) => new Promise(resolve => {
    console.log("playing:", el)
    return setTimeout(resolve, 1000)
})

// a dummy playlist
const playlist = Array(10).fill(0).map((_, i) => i);

// a setup function to orchestrate everything

function setup() {
  let breakLoop = false;
  return {
    async onPlay() {
      breakLoop = false;
      for (const el of playlist) {
        if (breakLoop) {
          break;
        }
        await play(el);
      }
    },
    onStop() {
        console.log("stopping")
      breakLoop = true;
    },
  };
}

// and use them after initialization
let { onPlay, onStop } = setup();

onPlay()
// stop after onPlay had some time to play (would normally be called from your "click" event handler)
setTimeout(onStop, 3000)
Abdellah Hariti
  • 657
  • 4
  • 8
  • Thx, but it doesn't work for me. The `breakLoop = true` in `onStop` doesn't take effect on the for-loop – rodbs Mar 15 '21 at 00:05
  • It does for me, retry now with the interactive code snippet to get a clearer idea of my approach – Abdellah Hariti Mar 15 '21 at 10:33
  • Not sure why it's not working for me. I'm using `onPlay()` and `onStop()` in functions executed when clicking on button (in React). `onStop` doesn't change `breakLoop` at `onPlay()` level. Apart from that I've observed if I use state variables it triggers a rerender and the `setup()` function is rexecuted. Should I put it inside an `useEffect` ? – rodbs Mar 16 '21 at 00:09
  • @AbdellahHariti, it works for you because you're not using react – Normal Sep 14 '22 at 16:00