如何在Ajax中从任何Api获取数据时计算获取时间

  1. I just want to show the amount of data fetched from Api.

  2. output should be like 10% fetched 90 % remaining like that.

  3. I'm searching how should I calculate the amount the amount retreived and remaning data left to be fetched.

  4. I have been working on basecamp api It would waste lots of time to fetch tasks , activities etc. So just want that I want to show time left while fetching in Ajax .

I have googled and found a link: Monitoring_progress but if any body could suggest to me where to start I would much appreciate.

As far as I know there is no way to get the exact time, but you can get an approximation.

Why you can't have an exact time ?

Most of the time is spent in the basecamp servers, not in the request. The link you posted offers a way for basecamp to push progress messages. If they don't do so, you will get nothing.

You can imagine the basecamp servers as a wall. Behind the wall is the progress, but you can't see behind a wall and you are not allowed by basecamp to climb it.

What to do ?

You can approximate this time. With a method similar to what is posted here:

var ajaxTime= new Date().getTime();
$.ajax({
    type: "POST",
    url: "some.php",
}).done(function () {
    var totalTime = new Date().getTime()-ajaxTime;
});

you can measure how long it will take to complete a request.

Than you calculate the mean time of all requests made to an url. That time will be good enough.

I recommend something like this:

  • Measure times by yourself for every request, 10 times.
  • Calculate the mean of the times ( sum them and divide by 10 (the number of requests))
  • Save the result and send it when you initiate your application and store in the browser.
  • When user makes request, get the precalculated time and display a timer.

Update

To display a fix amount of time as a percent you can do like this:

  • secondsPerPercent = timeInSeconds / 100 <-- this is how many seconds need to pass for a percent to be filled.
  • make a javascript timer (code for it can be found on google) that updates the percent every secondsPerPercent.