The Complete WebDeveloper (47 Blogs) Become a Certified Professional

Implementing JavaScript Countdown Timer In An Online Quiz Application

Last updated on Apr 14,2022 93.2K Views


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 ServletYou could also expand your Angular career opportunities by taking up Angular Certification Training.

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. To learn more check out this Full Stack developer course today.

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

Upcoming Batches For Web Developer Certification Training Course
Course NameDate
Web Developer Certification Training Course

Class Starts on 25th March,2023

25th March

SAT&SUN (Weekend Batch)
View Details
Comments
43 Comments
  • vikas says:

    please tell me… how to save result into database?

      • vikas says:

        Thankyou sir….can you please send me the code to save number of question,correct answers,time,date and exam type into database

  • Sanny says:

    Where is the DB file?

    • EdurekaSupport says:

      Hey Sanny, thanks for checking out our blog. You can get the the database file from this link: https://goo.gl/7eFRQR. Cheers!

  • sathish says:

    i am getting the action as null while running in the IE browser after clicking next but in eclipse it is running properly, please help me

    • EdurekaSupport says:

      Hey Sathish, thanks for checking out our blog. With regard to the issue you’re facing, please try using any other browser like chrome or Firefox or update the existing IE browser and check again. Do write to us if you face any further issue. Cheers!

  • sanjay says:

    i am getting nullpointer exception in main controller location is request.getSession().setAttribute(“totalNumberOfQuizQuestions”,document.getElementsByTagName(“totalQuizQuestions”).item(0).getTextContent()); here is showing the nullpointer exception.

    • EdurekaSupport says:

      Hey Sanjay, thanks for checking out the blog. Regarding your query, Null Pointer Exception means that you were trying to execute a function on a null pointer. What you can do is to figure out how far along the note you got. Remove each of the function calls one at a time until you figure out how and where is the null happening, and see if you can figure out why the value is returning null.
      request.getSession().setAttribute(“totalNumberOfQuizQuestions”,document.getElementsByTagName(“totalQuizQuestions”).item(0).getTextContent());
      Hope this helps.

  • Oloriire Oluwagbamila Philip says:

    the source code is not downloading.

    • EdurekaSupport says:

      Hey Oloriiee, thanks for checking out the blog. Please try downloading the source code now. The issue has been fixed. Cheers!

  • Sovon Chakraborty says:

    not going to the next question in exam. jsp
    what changes does it need?
    please tell me

      • EdurekaSupport says:

        Hi Sovon, somebody from our support team will definitely get in touch with you soon. Thanks for reaching out to us. Have a good day!

    • EdurekaSupport says:

      Hey Ibrahim, thanks for checking out the blog. Please try downloading the source code now. The issue has been fixed. Cheers!

    • bi kato says:

      hi sir, i can’t download source code, can send to my email: [email protected]

      thank you so much
      have a nice day

  • krishna says:

    please help me how to download code i am not finding download button

    • EdurekaSupport says:

      Hey Krishna, thanks for checking out the blog. Please try downloading the source code now. The issue has been fixed. Cheers!

  • Swapnil Akolkar says:

    how to run it

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Implementing JavaScript Countdown Timer In An Online Quiz Application

edureka.co