I'm programming a jQuery widget for a circular gauge (CSS3 growing with border radius, rotate and clip). I've got a lot of CSS/images/js on the page.
If I execute the widget code on DOM loading :
$(document).ready(function(){
$(".gauge").gauge();
});
I've got some timestamp problem and my code don't run properly. The timestamp timerFinish is always inferior to the new timestamp, so the seconds variable is negative, and percent is always superior to 120/150 so the code never execute... It's as the _create function runs at a time and the first setInterval (the _stopJauge fn) runs to much time after.
But if i do it like that:
$(window).load(function(){
$(".gauge").gauge();
});
The code works...
The problem is in the difference between timestamps.
If someone has an explanation of this comportment ?
Here is the code:
(function($){
$.widget("as.gauge", {
options: {
timerSeconds: 3
},
_create: function() {
var self = this;
this._startTimer();
},
_startTimer: function(){
var self = this;
this.timerFinish = new Date().getTime() + (this.options.timerSeconds * 1000);
log('Timerfinish : ' + this.timerFinish)
this.timer = setInterval(function(){
log("milli : "+new Date().getMilliseconds())
self._stopJauge();
}, 50);
},
_endTimer: function(){
clearInterval(this.timer);
},
_drawTimer: function(percent) {
var deg = 360 / 100 * percent;
percent = Math.round(percent);
this.element.html('<div class="percent"></div><div id="slice"' +
(percent > 50 ? ' class="gt50"' : '') +
'><div class="pie"></div>' +
(percent > 50 ? '<div class="pie fill"></div>' : '') +
'</div>'
).find('#slice .pie').css({
'-moz-transform' : 'rotate(' + deg + 'deg)',
'-webkit-transform' : 'rotate(' + deg + 'deg)',
'-o-transform' : 'rotate(' + deg + 'deg)',
'transform' : 'rotate(' + deg + 'deg)'
});
this.element.find('.percent').html('<span class="int">' + percent + '%</span>');
},
_stopJauge: function(data) {
var seconds = (this.timerFinish - new Date().getTime()) / 1000,
percent = 100 - ((seconds / this.options.timerSeconds) * 100);
log('stopJauge - getTime : ' + new Date().getTime());
log('timerfinish - new Date() = ' + (this.timerFinish - new Date().getTime()))
log('seconds : ' + seconds)
log('percent : ' + percent)
if (percent <= this.element.data('value')){
this._drawTimer(percent);
} else {
this.element.find('.percent .int').html(this.element.data('value') + '%');
this._endTimer();
}
}
});
}(jQuery));