i have an exam system in php on which i have set a countdown timer with the help of javascript. the questions are displayed one by one on the page and the timer reset to the initial position when the next question comes also the page refreshes itself. I want to set the timer on the decreasing state so is should not start again and again to the initial time. the code is the following i have written for the timer. please anyone help me to sort it out.
<div id="test_time">
<script language="javascript" type="text/javascript">
var min = 10;
var sec = 0;
var timer;
var timeon = 0;
function ActivateTimer() {
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = "Time Left : Minutes: " + min + " Seconds: " + sec;
document.getElementById("test_time").innerHTML =_time;
if (_time != "Time Left : Minutes: 0 Seconds: 0") {
if (sec == 0) {
min = min - 1;
sec = 59;
} else {
sec = sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
alert('Test Time Over.. Click Ok to get Results.');
window.location = "result.php";
}
}
</script>
</div>
First you must understand the concept of Jquery while working with the countdown timer and Quiz like PHP project.
You have to follow the following process in the System:
You have to load the question in AJAX.
You must have the div which loads the timer at the page load after the login is being done.
The timer div must not be loaded since the jquery will be keep loading if the page reloads again.
Only once the page has to be loaded that is after the login is done and after that the page should not be loaded and it has to changed inly with the help of AJAX.
Since if the question is loaded over the AJAX only the question div alone will be loaded and that to with AJAX and all the other part of the page will remain the same and you can maintain the timer in a correct manner.
Hope so you might be clear with the Explanations.
Happy Coding :)
Well , the above answer is the proper approach to the problem but still if you want it to work as it is, then you can prefer local Storage Variables.
Let this be home.php
<div id="test_time">
<script type="text/javascript">
var timer;
localStorage.min=10;
localStorage.sec=10;
var timeon = 0;
function ActivateTimer() {
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = "Time Left : minutes: " + localStorage.min + " seconds: " + localStorage.sec;
document.getElementById("test_time").innerHTML =_time;
if (_time != "Time Left : minutes: 0 seconds: 0") {
if (localStorage.sec == 0) {
localStorage.min = localStorage.min - 1;
localStorage.sec = 59;
} else {
localStorage.sec = localStorage.sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
alert('Test Time Over.. Click Ok to get Results.');
window.location = "result.php";
}
}
ActivateTimer();
</script>
</div>
<div>
Next Question
</div>
Let this be next_question_1.php
<div id="test_time">
<script type="text/javascript">
function Timer() {
var _time = "Time Left : minutes: " + localStorage.min + " seconds: " + localStorage.sec;
document.getElementById("test_time").innerHTML =_time;
if (_time != "Time Left : minutes: 0 seconds: 0") {
if (localStorage.sec == 0) {
localStorage.min = localStorage.min - 1;
localStorage.sec = 59;
} else {
localStorage.sec = localStorage.sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
alert('Test Time Over.. Click Ok to get Results.');
window.location = "result.php";
}
}
Timer();
</script>
</div>
<div>
<a href="next_question_2.php">Next Question
</div>
Since they are local Storage variables they carry on to next pages until you clear the cookies, you may add as many pages you want. This solves your problem but, I don't recommend such approach. AJAX is the proper way to do it. :)
Related
I am trying to do a simple redirect after x seconds on a page with a countdown timer. Every time I call the function I want the timer to be reset, however when i call it a second or third time the timer seems to have 3 different countdowns. Can anyone see why this is?
function delayRedirect(){
document.getElementById('countDown').innerHTML = 'Session Timeout In: <span id="countTimer"></span> seconds....';
clearInterval(sessionTimer);
var sessionTimer = null;
var timeleft = 60;
var sessionTimer = setInterval(function(){
timeleft--;
document.getElementById('countTimer').innerHTML = timeleft;
if(timeleft <= 0)
clearInterval(sessionTimer);
returnToLogin();
},1000);
}
Put the sessionTimer globally. What you currently do is re-declare sessionTimer every time you enter delayRedirect.
Working example:
const but = document.getElementById("but");
but.addEventListener("click", delayRedirect);
//define it globally
var sessionTimer = -1;
function delayRedirect() {
//clear it if it previously exists
clearInterval(sessionTimer);
sessionTimer = setInterval(function() {
console.log("sessionTimer " + sessionTimer);
}, 1000);
}
<button id="but">Run</button>
I feel like all the answers only address the Y part, not the X part, given that this is clearly an XY problem.
While the solution is to use a variable that isn't local to the function, solving the actual problem doesn't require clearing anything. One can simply use an interval to tick down, and reset the count to delay the redirect:
var timeleft = 60;
setInterval(function() {
if (--timeleft === 0) returnToLogin();
countTimer.innerHTML = timeleft;
}, 1000);
delay.onclick = function() {
timeleft = 60;
}
function returnToLogin() {
console.log("returning to login");
}
<p>Session Timeout In: <span id="countTimer">60</span> seconds....</p>
<button id="delay">Delay</button>
I am making a quiz game for a project in HTML and JavaScript. On every question, the player has 15 seconds to answer. I managed to do it like this:
<body onload="setTimeout(Timer,15000)">
and then in Js:
function Timer()
{
alert("You are out of time!");
}
However, I want to be able to display how much time the player has left in a <p> tag. How could I do that?
<div id="count">Start</div>
var count = 15;
var interval = setInterval(function(){
document.getElementById('count').innerHTML=count;
count--;
if (count === 0){
clearInterval(interval);
document.getElementById('count').innerHTML='Done';
// or...
alert("You're out of time!");
}
}, 1000);
Here's a basic example of a countdown timer
var count = 15;
var timer = setInterval(function() {
console.log(count);
count--;
if(count === 0) {
stopInterval()
}
}, 1000);
var stopInterval = function() {
console.log('time is up!');
clearInterval(timer);
}
Repl: https://repl.it/I2C6
Initialize the variable 'sec' with timeout time in seconds.
Call setInterval() which has 2 parameters, 1st is the method name and 2nd parameter is interval between invoking the method mentioned in 1st parameter.
var sec = 15;
var time = setInterval(myTimer, 1000);
function myTimer() {
document.getElementById('timer').innerHTML = sec + "sec left";
sec--;
if (sec == -1) {
clearInterval(time);
alert("Time out!! :(");
}
}
Time : <span id="timer"></span>
I am a beginner in javascript. There is a countdown timer in javascript, in which i wan to include a automatic form submit after duration ends. How can I do it? Please help me. The code is given bellow.
<script>
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
function tick() {
var counter = document.getElementById("clockdiv");
var current_minutes = mins-1;
seconds--;
var minutesSpan = counter.querySelector('.minutes');
var secondsSpan = counter.querySelector('.seconds');
minutesSpan.innerHTML = current_minutes.toString();
secondsSpan.innerHTML = (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
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(<?php echo $duration?>);
</script>
if(mins==0 && seconds==0){
form=document.getElementsByTagName("form")[0];
form.submit();
}
Add this into the countdown function.
If both minutes and seconds are 0 submit the first form found in your html.
As already shown on Stack Overflow:
How to set a timer using jQuery to sent HTTP post data of HTML form
You could use jQuery (include it in head tag):
setTimeout(function() { $('#form').submit(); }, 5000);
Where your form has id="form" and the delay is of 5s.
I'm trying to implement a script that essentially counts down from 30 seconds to 0, and at 0, redirects to the homepage. However, I noticed that my script only works on Firefox but not Chrome and Safari. On these browsers, the counter remains "stuck" at 30 seconds—never refreshing the HTML, but the redirect works fine. Not sure if I'm doing something wrong or if setInterval is not the right method for this kind of thing.
<script>
var seconds = 31;
var counter = setInterval("timer()", 1000);
function timer() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout("location.href='http://www.homepage.com';", 100);
return;
}
updateTimer();
}
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + " " + seconds + " " + "seconds";
}
</script>
Thanks in advance!
EDIT: So weirdly enough, my code (and all of yours) is working on JSFiddle, but it's just failing to "repaint" the HTMLinner when it's actually rendering the page. The seconds are changing fine (I outputted them to the console), the changes just aren't rendering.
Final Edit: This problem basically resulted from invalid CSS. I believe—the counter was running above the photo and I set the span to relative positioning with a higher z-index and top and bottom elements. I don't believe this is acceptable for something that is not a block.
Here's a working sample:
(function() { // wrapper for locals
var timer = document.getElementById("timer"),
seconds = 5,
counter = setInterval(function() {
if (--seconds < 1) {
clearInterval(counter);
timer.innerHTML = "Redirecting now...";
setTimeout(function() {
location.href = 'http://www.homepage.com';
}, 500);
} else {
timer.innerHTML = timer.innerHTML.replace(/\d+/, seconds);
}
}, 1000);
})();
<div id="timer">Redirecting in 5 seconds</div>
Here is a cleaner implementation with fewer defined functions (with demo):
<span id='timer'></span>
<script>
var seconds = 31;
setInterval(function() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout(function() {document.getElementById('timer').innerHTML = "redirecting..."}, 100);
return;
}
updateTimer();
}, 1000);
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + + seconds + " seconds";
}
<script>
Of course every JavaScript programmer should any opportunity to point out that "eval is evil" which includes passing a string to setInterval and setTimeout :)
Change your function to a variable, that worked for me:
<script>
var seconds = 31;
var counter = setInterval(timer, 1000);
var timer = function() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout("location.href='http://www.homepage.com';", 100);
return;
}
updateTimer();
}
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + " " + seconds + " " + "seconds";
}
</script>
I use the following example Redirect to redirect to a page. What i need is inside the image i would like to have a label or some text which should show count down from 30(secs) to 0(secs). I need javascript for this requirement.
Any help is appreciated
Hi include this before your existing DIV
<div id="myCounter">
</div>
Write the following Script
<script type="text/javascript">
var milisec = 0
var seconds = 30
document.getElementById("myCounter").innerHTML = '30';
function display() {
if (milisec <= 0) {
milisec = 9
seconds -= 1
}
if (seconds <= -1) {
milisec = 0
seconds += 1
}
else
milisec -= 1
document.getElementById("myCounter").innerHTML = seconds;
setTimeout("display()", 100)
}
display()
</script>
Adjust your DIV as per your need in the design by setting the position to absolute
<span id="myCounter"></span>
<script>
function counter (count) {
if (count > 0) {
document.getElementById("myCounter").innerHTML = count;
window.setTimeout(function() {counter(count-1)}, 1000);
} else {
window.location.href = "/redirected-page/";
}
}
counter(30);
</script>