Q:

Calculate difference between two times and increment the result

I am trying to calculate the difference between two times and increment the results. For these, I tried below code.

function toSeconds(time_str) {
        // Extract hours, minutes and seconds
        var parts = time_str.split(':');
        // compute  and return total seconds
        return parts[0] * 3600 + // an hour has 3600 seconds
            parts[1] * 60 + // a minute has 60 seconds
            +
            parts[2]; // seconds
    }

    var a = "12:00:00"
    var b = "13:05:02"

    var difference = Math.abs(toSeconds(a) - toSeconds(b));

    // format time differnece
    var result = [
        Math.floor(difference / 3600), // an hour has 3600 seconds
        Math.floor((difference % 3600) / 60), // a minute has 60 seconds
        difference % 60
    ];
    // 0 padding and concatation
    result = result.map(function (v) {
        return v < 10 ? '0' + v : v;
    }).join(':');
    alert(result);

Assume if start time 00:05 AM and end time 00:10 AM. If we calculate between these two times the result will be 5Minutes right. So we need to increment these like 00:05:00. Now onwards the time will increment from seconds, minutes and then Hours    
but it's working if giving 12 Hours format to calculate remaining hours. Is there any possibility to calculate the difference between two times and incrementing the result time.

A:

Is this what you want? I made a function that increments your result variable every 1 second using Javascript's setInterval. You can end the loop by calling clearInterval(x)

function toSeconds(time_str) {
        // Extract hours, minutes and seconds
        var parts = time_str.split(':');
        // compute  and return total seconds
        return parts[0] * 3600 + // an hour has 3600 seconds
            parts[1] * 60 + // a minute has 60 seconds
            +
            parts[2]; // seconds
    }

    var a = "12:00:00"
    var b = "13:05:02"

    var difference = Math.abs(toSeconds(a) - toSeconds(b));

    // format time differnece
    var result = [
        Math.floor(difference / 3600), // an hour has 3600 seconds
        Math.floor((difference % 3600) / 60), // a minute has 60 seconds
        difference % 60
    ];
    // 0 padding and concatation
//    result = result.map(function (v) {
//        return v < 10 ? '0' + v : v;
//    }).join(':');
    console.log(result);
    
   let x = setInterval(function() {
   result[2] = result[2] + 1;
   if(result[2]>=60){
    result[2] = 0;
    result[1] = result[1] + 1;
   }
   if(result[1]>=60){
    result[1] = 0;
    result[0] = result[0] +1
    }
    
    result[0] = result[0] === 24 ? 0 : result[0]
      
    console.log(result.map(function (v) {
        return v < 10 ? '0' + v : v;
    }).join(':'))
  
    }, 1000);

