0

I am trying to download a file from the server and want to calculate the time taken for that particular download and display it. Below is the code which is used to download but I am finding difficulty in calculating the time and displaying it. Important point is I might end up running the code several times on one click, I mean, the code should run for few times, say 15 times and I need to calculate time for every iteration and should display all the values to the user. Can anyone please help me in this? I am new to programming that’s why I might be asking very silly doubts but please don’t mind.

<html>

    <head>
    <script src="jQuery.js"></script>
    <script type="text/javascript">

    $.ajax({
        url: "input.txt",
        })

    .done(function(data){
        $("#textResponse").val(data);      
    })

   </script>
    </head>
    <body>
        <textarea rows="50" cols="90" id="textResponse"></textarea>
    </body>
</html>
SDM
  • 91
  • 2
  • 10

2 Answers2

2

$.ajax has a beforeSend callback. Can use that to attach the starting time to the jqXHR object. Then you can calculate difference of time within done callback vs start time:

$.ajax({
    url: '/echo/html/',
    beforeSend: function (xhr) {
        xhr.start = new Date().getTime();
    }        
}).done(function (res, status, xhr) {
    var end = new Date().getTime();
    var elapsed = end - xhr.start;
    $('body').append('<p>Elapsed =' + elapsed + ' (ms)</p>');
});

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thank you very much, I am trying to analyze the code. I think this is what I was looking for !! will get back to you if I find any difficulties. – SDM Dec 02 '13 at 02:27
  • Thank u so much, that's exactly what I wanted :) Appreciate the help. – SDM Dec 02 '13 at 02:42
1

Your problem can be solved using Date().getTime()

    <head>
    <script src="jQuery.js"></script>
    <script type="text/javascript">

    var start=new Date().getTime(); // Initializes the timer

    $.ajax({
        url: "input.txt",
        })

    .done(function(data){
        $("#textResponse").val(data);      
    })

    var end =new Date().getTime(); 
    var time=end-start; //calculates the time taken
    alert('Time taken for downloading the file: ' + time);

   </script>
    </head>
    <body>
        <textarea rows="50" cols="90" id="textResponse"></textarea>
    </body>
</html>

Now, if you want to run for certain times, you can set the loop, use the timer within the loop, store the time taken i.e time variable in an array and show the user the result of the array in the appropriate time as per your requirement. Reference: How to measure time taken by a function to execute

Community
  • 1
  • 1
Bibek Maharjan
  • 549
  • 2
  • 5
  • 15
  • Thanks but my main concern is to store the time value in an array and to display the time for every iterations on the screen and not in alert. can you please throw some light on that ? – SDM Dec 02 '13 at 02:19