Implementing JavaScript Countdown Timer In An Online Quiz Application

Recommended by 113 users

Jan 20, 2015
Implementing JavaScript Countdown Timer In An Online Quiz Application
Add to Bookmark Email this Post 48.3K    32

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.

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

Share on
Comments
32 Comments
  • Urmat

    HI! when i start project all pages loading to slow. How i can resolve it?

  • Sachin Kumar Gurjar

    Looks like something is missing in this code. Timer doesn’t work properly when i click on next button or prev. i am trying to read and put data to xml. What is this value ‘somevalue’ in custom submit function. where from it coming? Minute and second value is coming as null whjen passed from jsp to java…
    java.lang.NumberFormatException: For input string: “”
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at co.edureka.quiz.controller.ExamController.doPost(ExamController.java:69)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)

    • Ashish Jindal

      hey sachin same situation is mine.
      and when i start the exam there is no timer and no next aur previous button.
      As the Edureka show the user interface https://uploads.disquscdn.com/images/8ae80370388fc33f92897dea5d888d9ce17be26ac141c71c200632f865fa3a74.png

      when i start my exam only finish exam button display here and no timer

      can you please resolve this error http 500 and my buttons aur timer problems

      • EdurekaSupport

        Hey Ashish, thanks for checking out our blog. Could you please share your code so that we can review it and find the solution? Cheers!

        • Ashish Jindal

          can u send me your email id S, I can send You the code

          • EdurekaSupport

            Hey Ashish, you can either share it here or send it to support@edureka.co this one time only. Cheers!

          • Ashish Jindal

            hey Edu I have Send You on support@edureka.co this id which is given by you

            My Github Link So check this code
            and Pleaze Reply me and Mail Me the code or tell me where i write wrong code

            so after you correct my code as soon as Possible

          • EdurekaSupport

            We have received this Ashish, and will get back to you. Cheers!

          • Ashish Jindal

            hey edu u have provide me job id for my project but my problem is not resolve

          • Ashish Jindal

            plz help me as soon as possible for this online exam project query

    • EdurekaSupport

      Hey Sachin, thanks for checking out our blog. Could you please share your code so that we can review it and find the solution? Cheers!

24 X 7 Customer Support X

  • us flag 1-800-275-9730 (Toll Free)
  • india flag +91 88808 62004