app/assets/javascripts/timer.js
var Timer = {
seconds: 0,
selectorToUpdate: '#_timer_',
submitUrl: '', // only if no form on this page
nextTimeout: null,
heartbeatSent: false,
heartbeatSeconds: 0, // Time before end of timer when heartbeat is sent
heartbeatUrl: '',
updateDisplay: function() {
var min = Math.max(0, Math.floor(this.seconds/60));
var sec = Math.max(0, this.seconds % 60);
var minString = (min < 10 ? '0'+min.toString() : min.toString());
var secString = (sec < 10 ? '0'+sec.toString() : sec.toString());
$(this.selectorToUpdate).text(minString + ':' + secString);
},
initialize: function(seconds, submitUrl, heartbeatSeconds, heartbeatUrl) {
this.seconds = seconds;
this.submitUrl = submitUrl;
this.heartbeatSeconds = heartbeatSeconds;
this.heartbeatUrl = heartbeatUrl;
this.updateDisplay();
this.countdown();
},
countdown: function() {
this.nextTimeout = setTimeout('Timer.decrement()', 1000);
},
submitForm: function() {
clearTimeout(this.nextTimeout);
// if there's a form generated by @start_form_tag macro, submit it
if ($('form#_main').length > 0) {
$('form#_main').submit();
} else { // look for link with ID='submit' instead
window.location.href = this.submitUrl;
}
},
decrement: function() {
this.seconds -= 1;
this.updateDisplay();
if (this.seconds > 0) {
this.countdown();
if (this.seconds < this.heartbeatSeconds && !this.heartbeatSent) {
$.ajax({
type: "POST",
url: this.heartbeatUrl,
success: function(data, textStatus, jqXHR){
console.log("sucessfully sent heartbeat when timer was near zero");
},
error: function (data, textStatus, jqXHR){
console.log("failed to send heartbeat when timer was near zero");
}
});
this.heartbeatSent = true;
}
} else {
this.submitForm();
}
},
setup: function() {
var t = $('#_timer_');
if (t.length > 0) { // the page has a timer on it
Timer.initialize(t.data('countfrom'), t.data('submit'), t.data('heartbeatsecs'), t.data('heartbeaturl'));
}
},
};
$(Timer.setup);