SVG countdown dial

by jorgeluis

HTML

<div id="countdown" class="countdown">
    <label>0</label>
    <svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
     <g>
      <title>Layer 1</title>
      <circle id="circle" class="circle_animation" r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#6fdb6f" fill="none"/>
     </g>
    </svg>
</div>

CSS

.countdown {
    position: relative;
    width: 160px;
    height: 160px;
    float: left;
}

.countdown label {
    position: absolute;
    width: 100%;
    text-align: center;
    font: 40px/160px sans-serif;
    color: tomato;
}

svg {
   -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
}

#circle {
  fill: rgba(120,120,120,0.1);
  stroke-width: 8px;
  stroke: #6fdb6f;
  fill: none;
  stroke-dasharray: 440; /* this value is the pixel circumference of the circle */
  stroke-dashoffset: 440; /* these values need to match html attrs */
  transition: all 1s linear;
}

JavaScript

var startCountdown = function(time, callback) {
	// if( null == time ) return; // or time is not a number?
  var countdown = document.getElementById('countdown');
  var circ = countdown.querySelector('#circle'); 
  var radius = parseInt(circ.getAttribute('r'), 10); 
  var circumference = 2 * 3.14159 * radius + parseInt(circ.getAttribute('stroke-width'), 10);
	var i = 1;

// return alert(circ.style.strokeWidth);
	/* Need initial run as interval hasn't yet occured... */
	circ.style.strokeDashoffset = circumference - ( 1 * (circumference/time) );

	var interval = setInterval(function() {
      countdown.querySelector('label').textContent = i;
      if (i == time) {  	
        clearInterval(interval);
        if (typeof callback == 'function') {
 					callback(); 
				}
        return;
      }
      circ.style.strokeDashoffset = circumference - ( (i+1) * (circumference/time) );
      i++;  
  }, 1000);
}

startCountdown( 8, function() { alert('done'); } );