How to Play Audio After Few Seconds or Delay in JavaScript

By Saruque Ahamed Mollick

In this tutorial, I will show you how easily you can play audio after few seconds or some time delay easily using JavaScript.

Here we gonna create an HTML file with an audio tag and an audio src file. Then we will load it in our browser. Thereafter, We will create a JavaScript function to play that audio with some delay so that it plays after a certain period of time.

To see the video tutorial play this video

 

 

Play audio after few seconds in JavaScript

In this previous post How to Play Audio After The Page Loads in HTML With JavaScript I have described fully.

You can click on the above link to learn how to play audio after page load using JavaScript.

<script type="text/javascript">
    setTimeout(function(){
      document.getElementById("id_here").play();
      
    }, 8000)
  
  </script>

You can see, here I have used setTimeout function to achieve the delay.



 setTimeout(function(){ 
document.getElementById("id_here").play(); 
}, 8000)ods

This is the main function to play audio after 8 seconds.

 setTimeout(function(){ 
// your code goes here
}, enter delay time in miliseconds)

You may also interested in,

Alert Before Leaving A Web Page Using JavaScript jQuery

Bottom Sticky Music Player Source Code in JavaScript and CSS

To check if your function is working or not you can use console log.

console.log('your audio is started just now');

This line will add a console message when the audio starts playing.

You can test the below code

<!DOCTYPE html>
<html>
<head>
  <title>My Audio</title>

</head>
<body>
  <audio src="mysong.mp3" id="my_audio" loop="loop"></audio>
  <script type="text/javascript">
    setTimeout(function(){
      document.getElementById("my_audio").play();
      console.log('your audio is started just now');
    }, 8000)
  </script>
</body>
</html>

Just put your audio path in the src attribute.

loop will play the audio file repeatedly.

 

Leave a Reply

Your email address will not be published. Required fields are marked *