How to reset Time Countdown with logout? - javascript

I have created online quiz with MVC5 each question in single page the time countdown start when student start his exam from question one to end of exam.
this is the script:
<script type="text/javascript">
javascript: window.history.forward(1);
</script>
<script>
var timeoutHandle;
function countdown(minutes, stat) {
var seconds = 60;
var mins = minutes;
if (getCookie("minutes") && getCookie("seconds") && stat) {
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes", mins, 10)
setCookie("seconds", seconds, 10)
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
if (seconds > 0) {
timeoutHandle = setTimeout(tick, 1000);
} else {
if (mins > 1) {
setTimeout(function () { countdown(parseInt(mins) - 1, false); }, 1000);
} else {
window.location.replace("/StudentControl/LogOut");
return false;
}
}
}
tick();
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
window.location.replace("/StudentControl/LogOut");
}
}
return "";
}
window.onload = function startingTimer() {
//countdown(prompt("Enter how many minutes you want to count down:"),true);
var reqt = $("#reqtimer").val();
countdown(reqt, true);
}
</script>
every thing is working fine the problem is:
if the student end early and logout and other student use his computer ,login and start his exam the time will continue from the last time for the pervious student.
Is there any way to reset the browser history or reset the countdown with logout command?

Related

Countdown Timer to Add extra 2 minutes

I have created a countdown timer and am trying to add 2 minutes into the existing timer to extend the timer.
My Code
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
$(document).ready(function() {
var counter = 0;
var display = document.querySelector('#time'),
//timer = new CountDownTimer(600);
timer = new CountDownTimer(125); // for debug
timer.onTick(format).onTick(restart).start();
function restart() {
if (this.expired()) {
alert("Expired");
}
}
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
if (minutes < 2) {
if (counter == 0) {
alert("Extending Time");
counter++;
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span> minutes
I managed to trigger an event that after 2 minutes will show an alert that the time will be extended, but so far, I can't think of any method or functions I can use to add the extra time. Is there any way I can do this?
Add code as following:
CountDownTimer.prototype.reset = function (duration) {
this.duration = duration;
}
and rewrite function format as :
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
if (minutes < 2) {
if (counter == 0) {
//alert("Extending Time");
timer.reset(timer.duration + 120);
counter++;
}
}
}
You can add code in CountDownTimer.prototype.start before setTimeout like:
this.instance = setTimeout(...)
add function:
CountDownTimer.prototype.kill = function() {
clearTimeout(this.instance)
}
call function kill to stop timer permanently.

javascript counter with cookies doesn't work

I just tried to make a timer with cookies that makes a button only 3 times clickable (I had to do it with cookies cause it refreshes the page in its process), I made this timer but it doesn't work. Nothing on my page changed at all.
The code I have by //something else happens gets executed by the program.
Timer - (or at least what I thought that would work as a timer) :
mailagain.onclick = function () {
if (typeof getCookie("countIt") !== 'undefined') {
if (checkCookie("countIt") > 3) {
// something happens
} else {
//something else happens
var counter = checkCookie("countIt") + 1;
setCookie("countIt", counter, 1)
}
} else {
setCookie("countIt", 1, 1)
}
};
Coockie functions :
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie(name) {
var value = getCookie("name");
if (value != "") {
return value;
}
}
Some issues:
When reading the value from the cookie, be aware that it has the string data type. You need to convert it to number before comparing it with another number or adding 1 to it.
The function checkCookie is using the wrong (hard-coded) cookie name, but is even not necessary as a function. You can do all that with getCookie.
Here is a working version:
mailagain.onclick = function () {
// make sure to convert to number (unitary plus), or use 0 when it is not a number:
var counter = (+getCookie("countIt") || 0) + 1;
setCookie("countIt", counter, 1)
if (counter > 3) {
console.log('clicked too many times! (', counter, ')');
} else {
console.log('clicked ' + counter + ' number of times.');
}
};
var value = getCookie("name");
getCookie always return "undefined" because of wrong cookie name. Remove brakets.
function checkCookie(name) {
var value = getCookie(name); //here you go
if (value != "") {
return value;
}
}

Java script Timer CountDown

I'm creating java script count down timer and it works up to 60 seconds correctly and after that its not working.
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
var val = document.getElementById("LabelTimer");
if (val != null) {
var PopUpTimeDuration = 2;
countdown(parseInt(PopUpTimeDuration));
}
}
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1
seconds--;
counterVal.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
var result = counterVal.innerHTML;
if (result == "0:00") {
clearInterval(counter);
CloseIdlePage();
}
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
debugger;
if (mins >= 1) {
countdown(mins - 1);
}
}
}
tick();
}
When i run this program this start 1:59 and it continues up to 1:01. after that this display value rest to 1:59. (not 0:59). what i did wrong in here?
Fiddle demo is in Here: in here you can see two values are blinking each other
Here's how I'd implement this. Hopefully the comments are sufficient. It needs an element in the page with ID "counterDiv" to write the values to.
function quickCount(mins) {
// Keep some values in a closure
var el = document.getElementById('counterDiv');
var secs = 0;
// Helper to pad single digit numbers
function z(n){return (n<10? '0':'') + n}
// Keep a reference to the interval
var timer = setInterval(function() {
// Write the values
el.innerHTML = mins + ':' + z(secs);
// Decremement seconds
--secs;
// If finished a minute, decrement minut
if (secs < 0) {
if (mins) {
--mins;
secs = 59;
// If finsihed minutes too, cancel timer
} else {
timer && clearInterval(timer);
}
}
// Run at about every second
}, 1000);
}
window.onload = function() {
quickCount(2);
}
HTH
<head>
<script type="text/javascript">
function timer()
{
var val = document.getElementById("LabelTimer");
if (val !== null)
{
var PopUpTimeDuration = 2;
countdown(parseInt(PopUpTimeDuration));
}
}
function countdown(minutes)
{
var seconds = 60;
var mins = minutes;
function tick()
{
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1;
seconds--;
var t=current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
counterVal.value = t;
var result = counterVal.innerHTML;
if (result === "0:00")
{
CloseIdlePage();
}
if (seconds > 0)
{
setTimeout(tick, 1000);
}
else
{
if (mins > 1)
{
countdown(mins - 1);
}
}
}
tick();
}
</script>
</head>
<body>
<div>TODO write content</div>
<input type="text" id="LabelTimer" value="yooo">
<input type="text" id="lblCountDown">
<input type="button" value="try" onclick="timer();" />
</body>
I resolved this as follows:
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
var IsFunctionCalled = false;
function timer() {
var val = document.getElementById("LabelTimer");
if (val != null) {
var PopUpTimeDuration = 2;
if (IsFunctionCalled == false) {
IsFunctionCalled = true
countdown(parseInt(PopUpTimeDuration));
}
}
}
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1
seconds--;
counterVal.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
var result = counterVal.innerHTML;
if (result == "0:00") {
clearInterval(counter);
CloseIdlePage();
}
if (seconds > 0) {
setTimeout(tick, 1000);
// tick()
} else {
if (mins >= 1) {
countdown(mins - 1);
}
}
}
tick();
}
See here for Demo

How to make countdown timer not reset when refresh the browser?

When i refresh the browser, the timer resets, so how to make it not reset?
This is my code. Please check it.
<?php echo $waktune; ?> // You can change it into seconds
var detik = <?php echo $waktune; ?>;
if (document.images) {
parselimit = detik
}
function begintimer() {
if (!document.images)
return
if (parselimit < 12) {
document.getElementById("servertime").style.color = "Green";
}
if (parselimit == 1) {
document.getElementById("hasil").submit();
} else {
parselimit -= 1 curmin = Math.floor(parselimit / 60)
cursec = parselimit % 60
if (curmin != 0)
curtime = curmin + ":" + cursec + ""else
curtime = cursec + " detik"document.getElementById("servertime").innerHTML = curtime setTimeout("begintimer()", 1000)
}
}
Try to use session storage :
// Store
sessionStorage.setItem("key", "value");
// Retrieve
document.getElementById("result").innerHTML=sessionStorage.getItem("key");
Update
Example :
<head>
</head>
<body>
<div id="divCounter"></div>
<script type="text/javascript">
if (sessionStorage.getItem("counter")) {
if (sessionStorage.getItem("counter") >= 10) {
var value = 0;
} else {
var value = sessionStorage.getItem("counter");
}
} else {
var value = 0;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function () {
if (value >= 10) {
sessionStorage.setItem("counter", 0);
value = 0;
} else {
value = parseInt(value) + 1;
sessionStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(counter, 1000);
</script>
</body>
Store the server time in a cookie (see setcookie) and load that. You'll want to think about how long you want this cookie to last though.
You can use local storage, such as :
localStorage.setItem('countDownValue', curtime); // To set the value
...
curtime = localStorage.getItem('countDownValue'); // To get the value
I think you have to save some value in the cookie and reset timer only if timer > x && cookie is already been setted.
Set cookie on init:
setcookie("reloaded","true");
Set cookie on reaload:
setcookie("reloaded","false");
Check:
if($_COOKIE["reloaded"] == false && timer > $time) {
/* reset timer */
}
<form name="counter">
<input type="text" size="8" name="chandresh" id="counter">
</form>
<script type="text/javascript">
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var cnt = 60;
function counter(){
if(getCookie("cnt") > 0){
cnt = getCookie("cnt");
}
cnt -= 1;
document.cookie = "cnt="+ cnt;
jQuery("#counter").val(getCookie("cnt"));
if(cnt>0){
setTimeout(counter,1000);
}
}
counter();
</script>
Source: http://chandreshrana.blogspot.in/2017/01/how-to-make-counter-not-reset-on-page.html
How to create a countdown timer with JavaScript.
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
Try it yourself
Hope for help.

How to fix javascript countdown seconds bug

so I have this countdown timer I created,
<script type="text/javascript">
var interval;
var minutes = 12;
var seconds = 32;
window.onload = function() {
countdown('countdown');
}
function countdown(element) {
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
minutes=7;
seconds=47;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ':' : ':');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ?'':'';
el.innerHTML = minute_text + ''+seconds + ' '+second_text + ' remaining';
seconds--;
}, 1000);
}
</script>
The result works perfectly, but when the timer reaches digits below 10, (12:03, 12:05, etc.) it displays the seconds without a '0' in the front. (12:3 instead of 12:03)
I tried fixing this, but it has brought me nowhere. Is it possible to somehow edit my script to fix this bug?
second_text = (seconds > 9) ? (seconds) : ('0' + seconds);
I just cleaned your code a bit:
var interval,
minutes = 12,
seconds = 32;
window.onload = function() {
countdown('countdown');
}
function countdown(element) {
var el = document.getElementById(element),
minutes_text, second_text;
interval = setInterval(function() {
if(seconds == 0) {
if(minutes == 0) {
minutes=7;
seconds=47;
}
else {
minutes--;
seconds = 60;
}
}
minutes_text = minutes;
second_text = (seconds < 10 ? "0" : "") + seconds;
el.innerHTML = minutes_text + ':' + second_text + ' remaining';
seconds--;
}, 1000);
}
A number does not have a zero in front of it.
You have to manually add that.
if(seconds < 10) {
second_text = "0" + seconds;
}
try adding a function to pad the value displayed
function padvalue(i) {
if (i<10) {
i="0" + String(i);
}
return i;
}
Call it here
el.innerHTML = minute_text + '' + padvalue(seconds) + ' ' + second_text + ' remaining';
Use this snippet to convert the numbers to strings:
var secondStr = seconds + "";
while (secondStr.length < 2) {
secondStr = "0" + secondStr;
}
Do the same thing for minutes and hours and then print the strings.
(You do know that doing an interval of 1000 means the interval will be 1000 or more milliseconds? It's unlikely that you miss a whole tick though with that long of an interval. This means the counter will be close to real time seconds but not exact and will vary from time to time and computer to computer.)

Categories

Resources