Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (13.1k points)

I want to create a progress bar that has a duration and a percentage.

I want the progress bar to take 3000ms to finish i.e to get to 100%

This is my code so far:

  <div id="box"></div>

  <script>

     function start(){

          var duration = 5000; // it should finish in 5 seconds !

         var max = 100;

         var i = 0 ;

         var interval = setInterval(function(){

            i++;

            offset  = (max*i)/duration;

            console.log(offset);

            $("#box").css("width", offset + "px");

            $("#box").text(parseInt(offset) + "%");

            if(i>=duration){

                alert("done "+i);

                clearInterval(interval);

            }

        }, 1);

      }

  </script>

It works but it takes longer than 5000ms.

Can anybody help me with this?

1 Answer

0 votes
by (7k points)

The simplest solution to this is using JQuery’s .animate() function

Script tag:

function start() {

  var duration = 5000; // it should finish in 5 seconds !

  $("#box").stop().css("width", 0).animate({

    width: 100

  }, {

    duration: duration,

    progress: function(promise, progress, ms) {

      $(this).text(Math.round(progress * 100) + '%');

    }

  });

}

start()

Css:

#box {

  border: 1px solid red;

}

Body:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="box"></div>

Want to be a full stack developer? Check out the full stack developer course from Intellipaat.

Related questions

0 votes
1 answer
asked Apr 29, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Oct 4, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 13, 2019 in Python by Sammy (47.6k points)

Browse Categories

...