How to Play Audio After Few Seconds or Delay in JavaScript

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">
    }, 8000)

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

}, 8000)ods

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

// 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>
  <title>My Audio</title>

  <audio src="mysong.mp3" id="my_audio" loop="loop"></audio>
  <script type="text/javascript">
      console.log('your audio is started just now');
    }, 8000)

Just put your audio path in the src attribute.

loop will play the audio file repeatedly.

You may also read,

How to set audio playing time to starting position in JavaScript

Leave a Reply

Your email address will not be published.