This is an example of Javascript code to update and display the elapsed/remaining hours minutes and seconds in real-time.
Why?
I know there are a lot of articles out there that write about the same, but this is an example that I was coding and found to be one of the most reduced cut down formats I've made. I thought I'd make a note of it to not have to search elsewhere...
This example specifically displays the time remaining on an access_token which is generated from an OAuth 2.0 process. I want to display to the user how much time is left before another access token will be generated and how long ago was the last token created.
How?
So almost pure JS. I'm working out the seconds remaining and seconds elapsed in PHP first then passing these as two variables to the below code but you could get your values from anywhere:
- On page load, the seconds remaining and elapsed are specified
- JS then takes over and runs the time
var seconds_remaining = <?php echo ( filemtime($TOKEN_FILE)+3600 ) - time(); ?>; var seconds_elapsed = <?php echo time() - filemtime($TOKEN_FILE); ?>; setInterval('showTime()', 1000); function showTime(){ seconds_remaining--; seconds_elapsed++; if(seconds_remaining>=0){ document.getElementById("time_remaining").innerHTML = returnTime( seconds_remaining ); document.getElementById("time_ago").innerHTML = returnTime( seconds_elapsed ); } } function returnTime( s ){ hours = parseInt(s / 3600); s = (s % 3600); minutes = parseInt(s / 60); s = (s % 60); seconds = parseInt(s); str1 = ("0" + hours).slice(-2); str2 = ("0" + minutes).slice(-2); str3 = ("0" + seconds).slice(-2); return str1 + ':' + str2 + ':' + str3; }
- var seconds_remaining = <?php echo ( filemtime($TOKEN_FILE)+3600 ) - time(); ?>;
- var seconds_elapsed = <?php echo time() - filemtime($TOKEN_FILE); ?>;
- setInterval('showTime()', 1000);
- function showTime(){
- seconds_remaining--;
- seconds_elapsed++;
- if(seconds_remaining>=0){
- document.getElementById("time_remaining").innerHTML = returnTime( seconds_remaining );
- document.getElementById("time_ago").innerHTML = returnTime( seconds_elapsed );
- }
- }
- function returnTime( s ){
- hours = parseInt(s / 3600);
- s = (s % 3600);
- minutes = parseInt(s / 60);
- s = (s % 60);
- seconds = parseInt(s);
- str1 = ("0" + hours).slice(-2);
- str2 = ("0" + minutes).slice(-2);
- str3 = ("0" + seconds).slice(-2);
- return str1 + ':' + str2 + ':' + str3;
- }
The HTML would be something like:
<table> <tr><td>Time Remaining: </td><td id="time_remaining"></td></tr> <tr><td>Time Elapsed: </td><td id="time_elapsed"></td></tr> </table>
- <table>
- <tr><td>Time Remaining: </td><td id="time_remaining"></td></tr>
- <tr><td>Time Elapsed: </td><td id="time_elapsed"></td></tr>
- </table>