简体   繁体   中英

Play audio when javascript alert pops up and stop playing when the alert closes

I'm trying to play an audio when a javascript alert pops up and stop playing the audio when the user closes the alert. But the audio is not stopping when the user closes the alert.And the alert keeps appearing again and again even after I close it.

const audio = new Audio("sounds/Sparkle - Your Name.mp3");
audio.play();
audio.loop = false;
if(!alert("Time for some anime")){
           audio.pause();
}

you can use confirm() instead of alert()

const audio = new Audio("sounds/Sparkle - Your Name.mp3");
audio.play();
audio.loop = false;

function after() {
    audio.pause();
}

if(confirm("Time for some anime"))
    after();
else
    after();

or shorter with confirm("continue to pause")? after(): after(); confirm("continue to pause")? after(): after();

you can test it here:

https://jsfiddle.net/82wsqhuL/2/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM