Download File with Timer Count – Javascript

Share this Article

In several application you have seen that while downloading any file, images, videos, audios you will get a timer which takes the few seconds to do it’s downloading countdown. This is mainly you find at blog websites.

So inside this article we will see that How can we integrate a download file with time count or we can say How to add timer on downloading page? We will create a script which countdowns for 10 seconds and then automatically download the file.

Let’s get started.


Create a Simple HTML

Let’s say we have a page where download button is there. What we want ? When someone clicks on that download button, automatically the download process should be started after 10 seconds.

<button id="download-file" data-url="http://localhost/js/download.zip">Download Now</button>

Inside this piece of HTML we have a button with an ID attribute download-file and having a URL http://localhost/js/download.zip. This is the url which will be triggered automatically after 10 seconds.


Writing Javascript Code to Trigger Download

Next, we will have a on click event listener for the HTML button what we have created.

<!-- JavaScript part -->
<script type="text/javascript">
    // Total seconds to wait
    var seconds = 10;

    var downloadButton = document.getElementById("download-file");
    
    var download_url = downloadButton.getAttribute("data-url");

    downloadButton.addEventListener("click", download_button_event);

    function download_button_event() {

        var newElement = document.createElement("p");
        newElement.id = "countdown_seconds";
        newElement.innerHTML = "Automatically file will be downloaded in 10 seconds.";
        downloadButton.parentNode.replaceChild(newElement, downloadButton);

        download_timer();

    }

    function download_timer() {

        seconds = seconds - 1;

        if (seconds < 0) {
            // Download link
            window.location = download_url;
        } else {

            // Update remaining seconds
            document.getElementById("countdown_seconds").innerHTML = "Automatically file will be downloaded in " + seconds + " seconds.";
            // Countdown wait time is 1 second
            window.setTimeout("download_timer()", 1000);
        }
    }


</script>
  • On clicking button we are calling download_button_event function. This function is going to start the timer.
  • download_timer() This one is the timer function which decrements the timer second and once it the remaining seconds will be 0 then automatically data-url will be triggered.

We hope this article helped you to learn about Download File with Timer in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Leave a Comment