Published on Jul 31,2017
60.8K Views
Email Post

In this post we’ll extend our quiz application and add a JavaScript countdown timer functionality into it. Another thing we’ll implement here is, adding code so that each quiz can have different number of questions. If you haven`t already read the first part, I will recommend you to go through it. It will be easier for you to follow this post and understand it completely.

You can read the first part here Creating an Online Quiz Application using JSP Servlet.

JavaScript Countdown Timer

Time duration of each quiz is stored in the quiz XML file, we retrieve the duration of the quiz and save it in the user’s session as an attribute. When the user submits a question we also submit the time to the controller using custom form submission with JavaScript. So, when we show the next question we display the correct remaining time.

javascript-countdown-timer-online-quiz-application

When the time duration of the quiz is over, the user will be shown an alert box saying “Time Up” and the quiz will be evaluated and the final result will be displayed.

javascript-countdown-timer-online-quiz-application

Let`s see what we need to achieve this.

We have added two new lines in the quiz XML file, before quiz questions.

< quiz>
  < title>Java Quiz (2015/01/18)< /title>
  < totalquizquestions>10< /totalquizquestions>
  < quizduration>2< /quizduration>
    < questions>

      < question>
        < quizquestion>Which is the correct syntax ?< /quizquestion>
        < answer> public class ABC extends QWE extends Student< /answer>
        < answer> int i="A";< /answer>
        < answer>String s="Hello";< /answer>
        < answer> private class ABC< /answer>
        < correct>2< /correct>
      < /question>

      < question>
        < quizquestion> Which of the following a is not a keyword in Java ?< /quizquestion>
        < answer>class< /answer>
        < answer>interface< /answer>
        < answer>extends< /answer>
        < answer>abstraction< /answer>
        < correct>3< /correct>
      < /question>

      < question>
        < quizquestion>What is true about Java ?< /quizquestion>
        < answer>Java is platform specific< /answer>
        < answer>Java does not support multiple inheritance< /answer>
        < answer>Java does not run on Linux and Mac< /answer>
        < answer>Java is not a multi-threaded language < /answer>
        < correct>1< /correct>
      < /question>

      < question>
        < quizquestion>Which of the following is an interface ?< /quizquestion>
        < answer>Thread< /answer>
        < answer>Runnable< /answer>
        < answer>Date< /answer>
        < answer>Calendar< /answer>
        < correct>1< /correct>
      < /question>	

	  < question>
        < quizquestion>Which company released Java Version 8 ?< /quizquestion>
        < answer>Sun< /answer>
        < answer>Oracle< /answer>
        < answer>Adobe< /answer>
        < answer>Google< /answer>
        < correct>1< /correct>
      < /question>

     < question>
        < quizquestion>Java comes under which category of languages ?< /quizquestion>
        < answer>First Generation Languages< /answer>
        < answer>Second Generation Languages< /answer>
        < answer>Third Generation Languages< /answer>
        < answer>Fourth Generation Languages< /answer>
        < correct>2< /correct>
      < /question>

      < question>
        < quizquestion>Which is the default package that is automatically visible to your program ?< /quizquestion>
        < answer>java.net< /answer>
        < answer>javax.swing< /answer>
        < answer>java.io< /answer>
        < answer>java.lang< /answer>
        < correct>3< /correct>
      < /question>	 

     < question>
        < quizquestion>Which entry in WEB-INF is used to map a servlet ?< /quizquestion>
        < answer>servlet-mapping< /answer>
        < answer>servlet-registration< /answer>
        < answer>servlet-entry< /answer>
        < answer>servlet-attachment< /answer>
        < correct>0< /correct>
      < /question>	

     < question>
        < quizquestion>What is the length of Java datatype int ?< /quizquestion>
        < answer>32 bit< /answer>
        < answer>16 bit< /answer>
        < answer>64 bit< /answer>
        < answer>Runtime specific< /answer>
        < correct>0< /correct>
      < /question>	

     < question>
        < quizquestion>What is the default value of Java datatype boolean?< /quizquestion>
        < answer>true< /answer>
        < answer>false< /answer>
        < answer>1< /answer>
        < answer>0< /answer>
        < correct>1< /correct>
      < /question>	 	   

    < /questions>
< /quiz>

Setting Timer When Starting A New Exam

When the user starts a new exam, we set the total questions and duration of the quiz in the user`s session as an attribute.

request.getSession().setAttribute("totalNumberOfQuizQuestions",document.getElementsByTagName("totalQuizQuestions").item(0).getTextContent());
				request.getSession().setAttribute("quizDuration",document.getElementsByTagName("quizDuration").item(0).getTextContent());
				request.getSession().setAttribute("min",document.getElementsByTagName("quizDuration").item(0).getTextContent());
				request.getSession().setAttribute("sec",0);

Countdown Time

We have to decrement the timer after each second, to do that we are going to create a Javascript function that will be first called when exam page is loaded and then we will call that function recursively after each second to countdown time.

Javascript function to countdown time

< script language ="javascript" >
        var tim;       
        var min = '${sessionScope.min}';
        var sec = '${sessionScope.sec}';
        var f = new Date();

        function customSubmit(someValue){  
        	 document.questionForm.minute.value = min;   
        	 document.questionForm.second.value = sec; 
        	 document.questionForm.submit();  
        	 }  

        function examTimer() {
            if (parseInt(sec) >0) {

			    document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";
                sec = parseInt(sec) - 1;                
                tim = setTimeout("examTimer()", 1000);
            }
            else {

			    if (parseInt(min)==0 && parseInt(sec)==0){
			    	document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";
				     alert("Time Up");
				     document.questionForm.minute.value=0;
				     document.questionForm.second.value=0;
				     document.questionForm.submit();

			     }

                if (parseInt(sec) == 0) {				
				    document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";					
                    min = parseInt(min) - 1;
					sec=59;
                    tim = setTimeout("examTimer()", 1000);
                }

            }
        }
    < /script>

How to Call the Javascript Function

Now, to call that Javascript function we are going to use the onload attribute of body tag.

< body onload=”examTimer”>

Submitting the Quiz Time to Exam Controller

Until now we were submitting the quiz questions form directly to the Exam Controller, but now we have to send the timer parameters: minute and second also so that when Exam Controller displays the next question it should also display the correct remaining time. To achieve that we have submitted the form manually using Javascript and send the min and sec parameters to Exam Controller. 

Submitting Form Using Javascript

Note that when user click on next,previous or finish button customSubmit() Javascript function will be called.

< form action="exam" method="post" name="questionForm" >
 < c:forEach var="choice" items="${sessionScope.quest.questionOptions}" varStatus="counter">
 < input type="radio" name="answer" value="${counter.count}" >${choice}  < br/>
 < /c:forEach> < br/> 

 < c:if test="${sessionScope.quest.questionNumber > 0}">
 < input type="submit" name="action" value="Previous" onclick="customSubmit()" />
 < /c:if>

 < c:if test="${sessionScope.quest.questionNumber <  sessionScope.totalNumberOfQuizQuestions-1}">
 < input type="submit" name="action" value="Next" onclick="customSubmit()" />
 < /c:if> 

 < input type="submit" name="action" value="Finish Exam" onclick="customSubmit()" />

< input type="hidden" name="minute"/> 
< input type="hidden" name="second"/>

< /form>

customSubmit() function

It is the customSubmit() function that sends the minute and second parameters to ExamController.

  function customSubmit(someValue){  
        	 document.questionForm.minute.value = min;   
        	 document.questionForm.second.value = sec; 
        	 document.questionForm.submit();  
        	 }

Updating the Countdown Timer in User’s Session

We retrieve the values of minute and second parameters sent to the ExamController and update it in user`s session.

if(request.getParameter("minute")!=null)
			{			
			minute=Integer.parseInt(request.getParameter("minute"));
			second=Integer.parseInt(request.getParameter("second"));
			request.getSession().setAttribute("min",request.getParameter("minute") );
			request.getSession().setAttribute("sec",request.getParameter("second") );
			}

Handling the Time Up

When the duration of the quiz is over, in other words when both minute and second becomes zero.We show an alert box saying  “Time Up” and set the value of minute and second to zero and submit the form.

  if (parseInt(min)==0 && parseInt(sec)==0){
			    	document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";
				     alert("Time Up");
				     document.questionForm.minute.value=0;
				     document.questionForm.second.value=0;
				     document.questionForm.submit();

			     }

We have to change the code so that the exam will be finished when the time limit for the exam is over.

else if("Finish Exam".equals(action)||( minute==0 && second==0))
			{   finish=true;
				int result=exam.calculateResult(exam);				
				request.setAttribute("result",result);
				request.getSession().setAttribute("currentExam",null);
				request.getRequestDispatcher("/WEB-INF/jsps/result.jsp").forward(request,response);

			}

So, an exam can be finished either by clicking on the finish button directly or when time limit of the exam is over ( both minute and second becomes zero).

That’s it for this post.  In the next post we’ll further extend our quiz application and add new feature so that the user will be able to review his answers and know which questions he got it wrong and what were the correct answers.

As always you can download the code, change it as you like. That’s the best way to understand the code. If you have any question or request please comment below.

Click on the download button to download the code.

[buttonleads form_title=”Download Code” redirect_url=https://edureka.wistia.com/medias/v7u438czxx/download?media_file_id=66211710 course_id=44 button_text=”Download Code”]

Got a question for us? Please mention it in the comments section and we will get back to you.

Related Posts:

Get Started with Java/J2EE

Creating an Online Quiz Application using JSP Servlet

About Author
mahtab alam
Published on Jul 31,2017

Share on

Browse Categories

Comments
41 Comments