online quiz timer using Java Script - javascript

I am coding an online timed exam and for the timer to run I am using JS! The code for the timer to start and calculate the time and submit the exam when timer expires is as follows:
<script>
//Once the complete page is loaded the GIF image disappears and questions are displayed
function StartTimer()
{
document.getElementById('Loading').style.display = "none";
document.getElementById('Loaded').style.display = "block";
document.getElementById('1').style.display = "block";
document.getElementById('qustn1').style.backgroundColor="#dd6e23";
}
//Sets the Interval to the time
var ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
function submitForm()
{
document.getElementById("submit").submit();
}
function calculate_time()
{
var end_time = "<?php echo $_SESSION["start_time"]; ?>"; // Get end time from session variable (total time in seconds).
var dt = new Date(); // Create date object.
var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
var secs = total_time - (mins * 60); // Extract remainder seconds if any.
if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.
// Check for end of time, stop clock and display message.
if(mins <= 0)
{
if(secs <= 0 || mins < 0)
{
clearInterval(ct);
document.getElementById("txt").value = "0:00";
submitForm();
}
}
}
The above code runs well and even when the timer expires, the exam submits automatically. But, I am trying to call the setTimeOut() and setInterval() methods once the body is completely loaded i.e setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>); should be in the startTimer().
<body onload="StartTimer()">
......
<script>
.....
function StartTimer()
{
document.getElementById('Loading').style.display = "none";
document.getElementById('Loaded').style.display = "block";
document.getElementById('1').style.display = "block";
document.getElementById('qustn1').style.backgroundColor="#dd6e23";
var ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
}
.....
</script>
But when I do this, I am unable to execute the code exactly. Even though timer reaches 0:00 the exam cannot be submitted, instead negative timer is running!! Please help me!!

The problem is incorrect scope for variable ct in the second code. Actually, you should put this variable in a context that is available for *calculate_time* function.
For example, you can try out this code which moves variable ct to the out-most scope:
<body onload="StartTimer()">
......
<script>
.....
var ct = null;
function StartTimer() {
document.getElementById('Loading').style.display = "none";
document.getElementById('Loaded').style.display = "block";
document.getElementById('1').style.display = "block";
document.getElementById('qustn1').style.backgroundColor="#dd6e23";
ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
}
function submitForm() {
document.getElementById("submit").submit();
}
function calculate_time() {
var end_time = "<?php echo $_SESSION["start_time"]; ?>"; // Get end time from session variable (total time in seconds).
var dt = new Date(); // Create date object.
var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
var secs = total_time - (mins * 60); // Extract remainder seconds if any.
if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.
// Check for end of time, stop clock and display message.
if(mins <= 0) {
if(secs <= 0 || mins < 0) {
clearInterval(ct);
document.getElementById("txt").value = "0:00";
submitForm();
}
}
}
.....
</script>
......
</body>
The best way to find the root of problems like this, is using a javascript debugger like FireBug that will easily pinpoint the root of your problem.

I worked on a Online Quiz app where I have to implement timer.
I created one Javascript function that I call on body load
`< script language ="javascript" >
var tim;
var min = '${sessionScope.min}';
var sec = '${sessionScope.sec}';
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>
`
Value of variable min and sec are set by sessionVariable which hold the exam time in session.
The complete application with Timer functionality is available here
http://www.edureka.co/blog/creating-an-online-quiz-application-implementing-countdown-timer/

Related

How to implement a refresh status in Javascript?

So I'm trying to do a refresh status in which if the page was refreshed under 5 minutes, it would say "Updated Just Now," and if it was updated over 5 minutes ago, it would say, "Updated Moments Ago." Below is my Javascript:
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
if (seconds < 10) {
time = "Updated Just Now";
} else {
time = "Updated Moments Ago";
}
document.getElementById("demo").innerHTML = time;
}
window.onload = start
window.onload = end
However, it is very buggy and sometimes doesn't work at all. Any help will be appreciated.
Unless I missed something, I think You can use setTimeout. Initially set the HTML to 'Updated just now'.
const timeout = 5 * 60 * 1000
const changeText = () => {
document.getElementById("counter").innerHTML = "Updated moments ago";
}
setTimeout(changeText, timeout)
sandbox
You can simply do this instead of doing that stuff.
/* Note That 1000 is equivalent of 1 seconds */
setTimeout(function(){
document.getElementById("demo").innerHTML = "Updated Just Now";
}, 30000); /* This value is equivalent of 30 seconds */
setTimeout(function(){
document.getElementById("demo").innerHTML = "Updated Moments Ago";
}, 300000); /* This value is equivalent of 5 minutes */

Continuous Countdown Timer In Javascript or Jquery

I want to create a simple countdown timer in javascript or jquery.
I had implemented it using JS but what issue I am facing is if user refreshes the page then timer gets the refresh.
What I want is timer should not get the refresh.
Say timer is 5 min and if user refresh pages after 1 min the timer should continue to start from 4 min instead of 5 mins.
Here is code snippiet.
Its refresh the timer on page refresh.
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
countdown(2);
<div id="timer">2:00</div>
You just update the sessionStorage along with your counter and read it on starting the counter. Unfortunately the related snippet does not work on stackoverflow due to crossdomain policies - so here on codepen https://codepen.io/anon/pen/opNpVe
function countdown(seconds) {
seconds = parseInt(sessionStorage.getItem("seconds"))||seconds;
function tick() {
seconds--;
sessionStorage.setItem("seconds", seconds)
var counter = document.getElementById("timer");
var current_minutes = parseInt(seconds/60);
var current_seconds = seconds % 60;
counter.innerHTML = current_minutes + ":" + (current_seconds < 10 ? "0" : "") + current_seconds;
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
tick();
}
countdown(120);

Date difference in PHP

I'm trying to get a countdown system on my site that countdown only 24hrs from the time of registration.
The idea is after registration, a subscriber has 24hrs to make payment after which he will be blocked. I have the registration time already in my database but i'm stuck with the countdown. I've tried several help online but I don't seem to be getting it right.
The javascript is set to work with the seconds remaining for the user to make payment var count = '86400'; but i want to use php to calculate from the time registered till the current time how long he has left to register, so that when i refresh the page, it doesn't start from the current time left. So i did this var count = <?php echo strtotime($row_rsPH['date'])-time(); ?>;
<script type="text/javascript">
var count = <?php echo strtotime($row_rsPH['date'])-time(); ?>;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
}
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
</script>
<p>Time Left to make payment: <span id='timer'></span></p>
I used a countdown sample here http://www.hashemian.com/tools/javascript-countdown.htm and under TargetDate i used this php code
<?php
$date = date_create($row_rsPH['date']);
date_add($date, date_interval_create_from_date_string('1 days'));
echo date_format($date, 'Y-m-d h:i A');
?>
Hope this helps someone else

Recursive countdown timer

I'm trying to create a javascript counter that starts at 25 minutes and ends at 0. the idea is to show the minutes/seconds as a countdown clock on the page (my target div is called 'txt'). But I'm not getting my desired result - the timer does not subtract each time the function is run (every ms). Any ideas on where I'm going wrong? Code is below:
function countdown() {
var target = 1500000; // 25 mins
var current = 1000; // 0 secs
for (var i=0; i<5; i++) {
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
current = current+1000;
document.getElementById("txt").innerHTML = min + ":" + sec;
var t = setTimeout(countdown, 2500);}
}
}
You need to define current outside of your function. Currently you are resetting it to 1000 every time the function is run.
here you go:
var target = 1500000; // 25 mins
var current = 0; // 0 secs
function countdown() {
current += 1000;
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
document.getElementById("txt").innerHTML = min + ":" + sec;
if (diff > 0)
setTimeout(countdown, 1000);
}
countdown();
JSFiddle with running example: https://jsfiddle.net/epcmw0uc/5/

CountDown Script, Doesn't display or countdown correctly

so I've been tyring to debug my script for my pomodoro(tomato) clock. What I want this script to do is it will recieve input(in minutes). Right now what my script is doing is counting down by 5 instead of 1 seconds. Also it will not display the minutes like I want it too.
I made the script in a logical way to log to console and test it. What I see in the console is it displays every second, but it displays 5 seconds every second if that makes sense. Here is the jsbin: https://jsbin.com/gigohajawo/3/edit?js,consolehttps://jsbin.com/gigohajawo/3/edit?js,console
Here is the code, any help would be appreciated!!!
//makes sure the page is loaded first
$(document).ready(function() {
//global variables
//grabs text of an id and converts it to an int
var countMin = 5;
var count1 = 60;
//when button id "but" is clicked...
//while page is up, it keeps track each second that has passed
for(; countMin >=0;countMin--){
var counter1 = setInterval(function(){
//calls timer function to count down
count1 = Timer(count1,counter1,countMin);
},1000);
count1 =60;
}
//counts down
function Timer(count,counter,minutes){
count--;
//once it hits 0 seconds, the interval will stop counting
if(count <=0){
clearInterval(counter);
return count;
}
//displays the countdown
if(minutes < 10){
if(count < 10){
console.log("0:0" + count);
} else {
console.log("0:" + count);
}
}else if(minutes > 0 && minutes < 10){
if(count < 10){
console.log("0" + minutes +":0" + count);
} else {
console.log("0"+minutes+":" + count);
}
} else{
if(count < 10){
console.log(minutes+":0" + count);
} else {
console.log=minutes+":" + count;
}
}
return count;
}
});
This JSBin seems to do what you intended.
The code:
//makes sure the page is loaded first
$(document).ready(function() {
//global variables
//grabs text of an id and converts it to an int
var count1 = 120;
// Call a function every 1000 milliseconds (1 second)
var counter1 = setInterval(function() {
count1 = Timer(count1, counter1);
}, 1000);
//counts down
function Timer(count,counter){
// Decrement the seconds counter
count--;
// Get the minutes and seconds in whole numbers
var minutes = Math.floor(count / 60);
var seconds = count % 60;
// Once it hits 0 seconds, the interval will stop counting
if(count <=0){
clearInterval(counter);
}
// Pads the seconds with a 0
if (seconds < 10) {
seconds = "0" + seconds;
}
// Pads the minutes with a 0
if (minutes < 10) {
minutes = "0" + minutes;
}
//displays the countdown
console.log(minutes + ":" + seconds)
return count;
}
});
Please note:
Since you have defined count1 as a global variable you do not need to pass it into Timer
The same goes for counter1
If I was rewriting it I would do something like this:
//makes sure the page is loaded first
$(document).ready(function() {
var timeInSeconds = 120;
var timeCounter = setInterval(function() {
timeInSeconds--;
// If we hit 0 seconds clear the timer
if (timeInSeconds <= 0) {
clearInterval(timeCounter);
}
// Display the current time
displayTime();
}, 1000);
function displayTime(){
// Get the minutes and seconds in whole numbers
var minutes = Math.floor(timeInSeconds / 60);
var seconds = timeInSeconds % 60;
// Pad with zeros using the Ternary operator
seconds = (seconds < 10) ? "0" + seconds : seconds;
minutes = (minutes < 10) ? "0" + minutes : minutes;
// Display the countdown
console.log(minutes + ":" + seconds)
}
});

Categories

Resources