javascript - Creating a countdown timer in Rails that resets on the backend -


i creating rails quiz application timer counts down seconds left answer question.

in first version, did simple way: creating variable timer, instance seconds, , making part of quiz's javascript, so:

quiz = function() {   this.quizcurrent = 0;   this.score = 0;   this.seconds = 10;   this.timing = this.seconds;   this.container = $('#trivia');   this.participationid = null;  }   quiz.prototype.init = function() {   $('#trivia').on('click', '.btn.btn-primary-questions', this.checkanswer.bind(this));   $('div.timer strong').text(this.seconds)    this.start();  } 

i move backend using rails. previous question references countdown gem, seems present 2 issues:

1) need repeatedly call date/time , validate each question (which don't think can countdown), and;

2) ideally pass value javascript variable.

in documentation gem, shows how can pass countdown time view directly. however, using countdown value (in other words, when hits zero) force user next question while recording wrong answer, below, part of validation:

quiz.prototype.timer = function() {  var = this;   this.timing--;    $('div.timer strong').text(this.timing);    if (this.timing <= 0) {      self.stop();    $.getjson('/api/skip_question/' + this.participationid, function() {     that.nextquestion();    })   }} 

any ideas on how can "check" time on backend while still having quiz check make sure time hasn't run out?

i don't know countdown gem, simple solution comes mind.

lets keep timestamp on backend , when js quiz starts lets end know quiz has started.

$.getjson('/api/start_quiz/', function() {     //do whatever javascript starts quiz. }) 

on backend, lets assume have quizattempt model corresponding database value 'attempt_timestamp':

def start_quiz   quizattempt.create(user_id: current_user.id, attempt_timestamp: time.now) end 

then have before filter determines if time has run out on skip_question , answer_question endpoints. (in example there's 8 minute time limit.

before_filter :check_time, only: [:skip_question, :answer_question]  def check_time   #get last attempt   last_attempt = quizattempt.where(user_id: current_user.id).last   if (last_attempt.attempt_timestamp + 8.minutes) < time.now     #time     return false   end end 

side idea: add endpoint responds recorded timestamp purpose of syncronizing js clock timestamp in db.

edit: possible place keep said timestamp might in session rather database.


Comments