Countdown Time Display

I came across this progress code on this site .

What I want to do is do a 3 minute countdown and show how many minutes and seconds are left. Therefore, instead of displaying the percentage, I want to display the remaining time.

I am using the following code:

Js

progress(100, $('#progressBar')); // This is what the timer should update each second

function progress(percent, $element) {
    var progressBarWidth = percent * $element.width() / 100;
    $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + " minutes/seconds to go");
};

HTML

<div id="progressBar">
  <div></div>
</div>

CSS

 #progressBar {
  width: 923px;
  margin: 10px auto;
  height: 22px;
  background-color: #0A5F44;
}

#progressBar div {
  height: 100%;
  text-align: right;
  padding: 0 10px;
  line-height: 22px; /* same as #progressBar height if we want text middle aligned */
  width: 0;
  background-color: #CBEA00;
}
+4
source share
1 answer

You need to change this function a bit:

  • Use the 3 parameters ( timeleft, timetotal, element) instead of the actual 2
  • Use setTimeout()to update the progress bar every second.
  • Check timeleftto see if update progress bar.
function progress(timeleft, timetotal, $element) {
    var progressBarWidth = timeleft * $element.width() / timetotal;
    $element
        .find('div')
        .animate({ width: progressBarWidth }, 500)
        .html(timeleft + " seconds to go");
    if(timeleft > 0) {
        setTimeout(function() {
            progress(timeleft - 1, timetotal, $element);
        }, 1000);
    }
};

progress(180, 180, $('#progressBar'));

, CSS, , :

#progressBar div {
  box-sizing: border-box;
}

JSFiddle

[]

, , :

.animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, "linear")

JSFiddle

+15

Source: https://habr.com/ru/post/1546852/


All Articles