Calculate Elapsed Time of a Function in jQuery

Posted on September 29, 2019 at 4:56 pm

Here is how to calculate elapsed time of a function in jQuery:

function secondsTimeSpanToHMS(s){ var h = Math.floor(s/3600); s -= h*3600; var m = Math.floor(s/60); s -= m*60; return h+":"+(m < 10 ? '0'+m : m)+":"+(s < 10 ? '0'+s : s); }
 
var seconds = 1;
 
$('#elapsed-time').html('Elapsed time: ' + secondsTimeSpanToHMS(seconds)).show();
 
interval = setInterval(function(){ $('#elapsed-time').html('Elapsed time: ' + secondsTimeSpanToHMS(++seconds)) }, 1000);
 
...
 
clearInterval(interval);

We initiate an interval via setInterval() so every second it updates elapsed time.

Then once our code/function has finished we use clearInterval() to stop the interval.

We use secondsTimeSpanToHMS() to convert seconds to H:M:S.

Receive updates via email

Other Posts

Updated Posts