Run the function only once if its been called 50 times in 1 second Code Answer

This is the function and what is does, is playing a sound when new order is coming. So there be 50 orders coming all at once, now it play the sound 50 times, where only 1 time is enough. Any idea how I can achieve this?

function playSound() {
    var audio = new Audio('/audio/short_notification.mp3');
    audio.play()
}

Found some similar questions but they did not provide a much of help on this.

Answer

Use setTimeout function to reset variable that controls the audio play.

let isPlaying = true;
const silentTimeOutCounter = 1000;

function playSound() {
    if(isPlaying){
      var audio = new Audio('/audio/short_notification.mp3');
      audio.play();
      isPlaying = false;
      setTimeout(() => {isPlaying = true;} ,silentTimeOutCounter);
    }
}

playSound();

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji