86

I would like a line that says:

Your download will begin in (10, 9, 8, etc. Beginning on page load) seconds.

I already have the 10 second download text set up, and I have looked at other stackoverflow posts. They all include CSS, and Jquery. I would like just a Javascript/HTML timer.

No other requests have been made for a simple line stating "You're download will begin in x seconds". How would I do this?

  • 1
    possible duplicate of [Code for a simple JavaScript countdown timer?](http://stackoverflow.com/questions/1191865/code-for-a-simple-javascript-countdown-timer) – Ken Herbert Jun 29 '15 at 00:34
  • JavaScript timer functions all work in milliseconds, so you are going to have to work in milliseconds at some point in time in your code. – Ken Herbert Jun 29 '15 at 00:55
  • 1
    If you used the code in the answer below, then you used milliseconds in the `},1000);` line. – Ken Herbert Jun 29 '15 at 00:56

6 Answers6

192

JavaScript has built in to it a function called setInterval, which takes two arguments - a function, callback and an integer, timeout. When called, setInterval will call the function you give it every timeout milliseconds.

For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.

function makeAlert(){ 
    alert("Popup window!");
};

setInterval(makeAlert, 500);

However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.

setInterval(function(){ alert("Popup window!"); }, 500);

Once setInterval is called, it will run until you call clearInterval on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.

var timeleft = 10;
var downloadTimer = setInterval(function(){
  if(timeleft <= 0){
    clearInterval(downloadTimer);
  }
  document.getElementById("progressBar").value = 10 - timeleft;
  timeleft -= 1;
}, 1000);
<progress value="0" max="10" id="progressBar"></progress>

Alternatively, this will create a text countdown.

var timeleft = 10;
var downloadTimer = setInterval(function(){
  if(timeleft <= 0){
    clearInterval(downloadTimer);
    document.getElementById("countdown").innerHTML = "Finished";
  } else {
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
  }
  timeleft -= 1;
}, 1000);
<div id="countdown"></div>
James McDowell
  • 2,668
  • 1
  • 14
  • 27
  • 3
    This is an elegant solution. To make the progress smoother you can of course reduce the timer (e.g. from 1000 to 100) and increase the time (e.g. from 10 to 100). – Mike Poole Feb 23 '20 at 13:18
67

This does it in text.

<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>

<script type="text/javascript">
    var timeleft = 10;
    var downloadTimer = setInterval(function(){
    timeleft--;
    document.getElementById("countdowntimer").textContent = timeleft;
    if(timeleft <= 0)
        clearInterval(downloadTimer);
    },1000);
</script>
Teddy Koker
  • 954
  • 6
  • 8
13

A solution using Promises, includes both progress bar & text countdown.

ProgressCountdown(10, 'pageBeginCountdown', 'pageBeginCountdownText').then(value => alert(`Page has started: ${value}.`));

function ProgressCountdown(timeleft, bar, text) {
  return new Promise((resolve, reject) => {
    var countdownTimer = setInterval(() => {
      timeleft--;

      document.getElementById(bar).value = timeleft;
      document.getElementById(text).textContent = timeleft;

      if (timeleft <= 0) {
        clearInterval(countdownTimer);
        resolve(true);
      }
    }, 1000);
  });
}
<div class="row begin-countdown">
  <div class="col-md-12 text-center">
    <progress value="10" max="10" id="pageBeginCountdown"></progress>
    <p> Begining in <span id="pageBeginCountdownText">10 </span> seconds</p>
  </div>
</div>
treckstar
  • 1,956
  • 5
  • 21
  • 26
1

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      ProgressCountdown(10, "pageBeginCountdownText");

      function ProgressCountdown(timeleft, text) {
        return new Promise((resolve, reject) => {
          var countdownTimer = setInterval(() => {
            timeleft--;

            document.getElementById(text).textContent = timeleft;

            if (timeleft <= 0) {
              clearInterval(countdownTimer);
              resolve(true);
            }
          }, 1000);
        });
      }
    </script>

    <style>
      .dot {
        height: 100px;
        width: 100px;
        border-style: solid;
        border-width: 2px;
        border-radius: 50%;
        display: inline-block;
        text-align: center;
      }

      .clock {
        text-align: center;
      }
      .pp {
        text-align: center;
      }

      
    </style>

    <div class="row begin-countdown">
      <div class="col-md-12 text-center">
        <div class="dot" style="position: center">
          <h3 id="pageBeginCountdownText" class="clock">10</h3>
          <p class="pp">Seonds</p>
        </div>
      </div>
    </div>
  </body>
</html>
Gfx Help
  • 11
  • 1
-1

var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');
    var total_timers = seconds_inputs.length;
    for ( var i = 0; i < total_timers; i++){
        var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
        var cal_seconds = seconds_inputs[i].getAttribute('value');

        eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
        eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
    }
    function timer() {
        for ( var i = 0; i < total_timers; i++) {
            var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');

            var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
            var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
            var hours = Math.floor(hoursLeft / 3600);
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
            var minutes = Math.floor(minutesLeft / 60);
            var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;

            function pad(n) {
                return (n < 10 ? "0" + n : n);
            }
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
            document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
            document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
            document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);

            if (eval('seconds_'+ seconds_prod_id) == 0) {
                clearInterval(countdownTimer);
                document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
            } else {
                var value = eval('seconds_'+seconds_prod_id);
                value--;
                eval('seconds_' + seconds_prod_id + '= ' + value + ';');
            }
        }
    }

    var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
    <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
    <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
    <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
    <div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>
</div>
CodingEra
  • 1,313
  • 10
  • 20
-4

var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');
    var total_timers = seconds_inputs.length;
    for ( var i = 0; i < total_timers; i++){
        var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
        var cal_seconds = seconds_inputs[i].getAttribute('value');

        eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
        eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
    }
    function timer() {
        for ( var i = 0; i < total_timers; i++) {
            var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');

            var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
            var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
            var hours = Math.floor(hoursLeft / 3600);
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
            var minutes = Math.floor(minutesLeft / 60);
            var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;

            function pad(n) {
                return (n < 10 ? "0" + n : n);
            }
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
            document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
            document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
            document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);

            if (eval('seconds_'+ seconds_prod_id) == 0) {
                clearInterval(countdownTimer);
                document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
            } else {
                var value = eval('seconds_'+seconds_prod_id);
                value--;
                eval('seconds_' + seconds_prod_id + '= ' + value + ';');
            }
        }
    }

    var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
    <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
    <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
    <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
    <div class="seconds box"> <span class="key" id="deal_sec_1">0p0</span> <span class="value">SEC</span> </div>
</div>