Thursday, April 13, 2017

Quick Javascript Timer

Example of a quick hh:mm:ss timer


<!doctype html>
<html>
<head><title>Timer After 10 seconds</title>
<style>
body{font-family: Arial; line-height: 1.5em; color: #333;}
.timer{font-size: 100px; line-height: 120px;}
</style>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
</head>
<body>
<h1>Hour Min Timer Example</h1>
<p>
<ul>
 <li>Timer should appear after 10 seconds of lapse of user inactivity with mouse and keyboard</li>
 <li>Timer format can be hh:mm:ss or hh:mm.
 <li>Second value that is updated at every second is an intuitive indicator that this is a timer.
</ul>
</p>
<div class="timer">
 <span class="timeOutput" id="timeOutput"></span>
</div>
<script>

// Reset and tick every second
var my = my || {};

my.friendlyTime = function( sec ){

 this.ss = "0" + (sec % 60);
 this.ss = this.ss.substring( this.ss.length-2, this.ss.length );
 this.mm = "0" + Math.floor( sec / 60 ) % 60;
 this.mm = this.mm.substring( this.mm.length-2, this.mm.length );
 this.hh = "0" + Math.floor( sec / 3600 );
 this.hh = this.hh.substring( this.hh.length-2, this.hh.length );
};

my.display_time_since_pageload = function( initial_delay_sec, display_format, display_selector){
 /*
  initial_delay_sec: seconds to wait to display the ellapsed time
  display_format: "hh:mm:ss" or "hh:mm"
  display_selector: location to display the elapsed time. must be jQuery-format selector
 */
 var totalSec = 0;

 setInterval(function(){
 
  totalSec++;
  //console.log( "totalSec = " + totalSec );
  
  if( totalSec >= initial_delay_sec ){

   var t = new my.friendlyTime( totalSec );

   if(display_format == "hh:mm:ss") {
    $(display_selector).html( t.hh + ":" + t.mm + ":" + t.ss );
   }
   if(display_format == "hh:mm") {
    $(display_selector).html( t.hh + ":" + t.mm );
   }
   //console.log( "t.hh = " + t.hh + ", t.mm = " + t.mm + ", t.ss = " + t.ss ); 
  }
  
 }, 1000);
};

$(function(){
 my.display_time_since_pageload( 10, "hh:mm:ss", "#timeOutput" );
});

</script>


</body>
</html>


No comments: