Thursday, June 26, 2014

Calculating time left in minutes using Javascript

I was creating a mobile app and had a need to be able to show the available time that is left after the user has set the amount of time they have to do something. The code snippet below is from my class:
setEndTime: function(){
        var start_time = new Date();        
        Tracker.start_time = start_time;
        
        var end_time = new Date( start_time.getTime() + ( parseInt(Guests.available_time)*60000 ) );
        Tracker.end_time = end_time;
    },
    
    calculateAvailableTime: function(){
        var current_time = new Date();        
        var difference = current_time - Tracker.start_time;
        difference /= 1000;
        var time_passed = Math.round(difference / 60 );   
        var time_left = parseInt(Guests.available_time) - time_passed;
        Tracker.time_left = time_left;
        var time_value = ( time_left > 1 ) ? " mins" : " min";
        $("#time_left").html(time_left + time_value);
    },
This is how it works. The user sets the time which is Guests.available_time. Upon clicking the button to set the time available, I call the setEndTime function which uses the Javascript date object to capture the time. I set it globally in another class. I then calculate the end time by using the new Javascript object and adding the time available to it. I multiply by 60000 to convert it to timestamp. To get the time that is left, I used a case to capture the page name and then call the calculateAvailableTime function which takes the current time using the Javascript object and then I calculate the difference by subtracting the start time from it. I divide the difference by 1000 to remove the milliseconds then I divide by 60 to get the minutes. I then subtract it from the time that the user had set to get the time that is left.

No comments: