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.
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();
You can set timer
and check if the function was called in the last second.
let timer = 0; function playSound() { if (Date.now() - timer < 1000) return; timer = Date.now(); var audio = new Audio('/audio/short_notification.mp3'); audio.play(); }
You can use a global variable var to check if it is played once.
var isPlayedOnce = false;
function playSound() {
if(!isPlayedOnce){
var audio = new Audio('/audio/short_notification.mp3');
audio.play();
isPlayedOnce = true;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.