How to prevent executing setTimeout function of the previous card on the next card if I switched to the next card before that setTimeout timer has been elapsed?

Hello. I’m trying to create a card design of my own. On the back of a card, there will be 6 audio files and I want them to sound with a specific order. The first played audio will be the first one from the list, but the second played audio should be random from the 5 left ones.
As Anki doesn’t support the play() and onended() methods for audio files I have to use the click() and setTimeout() functions respectively in order to manually control the playback of audios.
A problem occurs when I use the setTimeout() function. There is a three-second delay after which the second audio should be played. But if I press Good and switch to the next card before these 3 seconds have elapsed, that setTimeout function from the back of the previous card will be executed on the front of the next card. So, the audio from the back of the card will be played on the front of the next card.
Is there any way to prevent it from happening?

Here is the simplified card design:
Front:

{{Front}}

Back:

{{Audio 1}}
{{Audio 2}}

<script>
  {

    const audios = document.querySelectorAll(".soundLink");
    audios[0].click();

    setTimeout(() => {
      audios[1].click()
    }, 3000)

  }
</script>

PS: The “Don’t play audio automatically” option should be enabled in the deck settings.

Update: Using the clearTimeout() function on the front of a card doesn’t help.

{{Front}}

<script>
{
  clearTimeout(timer);
}
</script>
{{Audio 1}}
{{Audio 2}}

<script>
{
  const audios = document.querySelectorAll(".soundLink");
  audios[0].click();
  let timer = setTimeout(()=>{audios[1].click()}, 3000)
}
</script>
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.