-3

I have an async function that gets an array of objects, I set a soundOn to true if:

soundOn = content.some(ele => ele.order_status === 'processing');

It works partly, e.g. plays sound when above is true - however continues to play even if soundOn evaluates to false. Here's the rest of my code.

function getOrders()
{
 (async () => {
    bgSound = new Audio("assets/sounds/spn.mp3");
    soundOn = "";
    const resp = await fetch(url+'/app/v1/post', {
    //truncated
    });
    const content = await resp.json();
    if(content.length > 0)
    {
    soundOn = content.some(ele => ele.order_status === 'processing');
    }
    (soundOn) ? setInterval(function () { bgSound.play() }, 5000) : bgSound.pause();
 })();
 setTimeout(getOrders, 30000);
}

content array looks like this (part of it).

[{"id":"1","order_status":"acknowledged", "type":"off"},
{"id":"1","order_status":"processing", "type":"off"},{"id":"1","order_status":"processing", "type":"off"}]

while the app is running those statuses get updated to acknowledged but the sound continues to play. I am not sure why this is the case, any help would be appreciated.

Abu Nooh
  • 846
  • 4
  • 12
  • 42
  • You are adding an interval that runs every 5 seconds and you never clear it. So even when your condition is false the interval is still running. And `bgSoung` is a new audio, so pausing it won't pause the old one – Konrad Jan 29 '23 at 13:00
  • any alternatives you can suggest? – Abu Nooh Jan 29 '23 at 13:08

1 Answers1

-1

Adding a condition might help:

(soundOn) ? setInterval(function () { if (soundOn) bgSound.play() }, 5000) : bgSound.pause();
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 31 '23 at 08:12