Countdown timer on Label for 30 seconds using Javascript - javascript

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>

Related

How to set javascript timer back to ZERO upon page reload

I am using this timer with a page loader. The problem is if a page finishes loading before the timer is up, then the next time you load the page, the timer starts where it left off the last time the page executed. I need to make sure the count variable is set to zero on page re-load. Thanks in advance
<script>
var myVar=setInterval(function(){myTimer()},1);
var count = 0;
function myTimer() {
if(count < 100) {
$('.progress').css('width', count + "%");
count += 0.025;
document.getElementById("demo").innerHTML = Math.round(count) +"%";
// code to do when loading
} else if(count > 100) {
// code to do after loading
count = 0;
}
}
</script>
You can wrap your code into a function which will reset the counter and start it again:
<script>
var myVar;
var count;
function restartTimer() {
count = 0;
clearInterval(myVar);
myVar = setInterval(function(){ myTimer() }, 1);
}
function myTimer() {
if(count < 100) {
$('.progress').css('width', count + "%");
count += 0.025;
document.getElementById("demo").innerHTML = Math.round(count) +"%";
// code to do when loading
} else if(count > 100) {
// code to do after loading
count = 0;
}
}
</script>
And now you just need to call restartTimer function wherever you want:
resetTimer();
In your case, you need to call it before every call to PHP page.

countdown timer reset on each page

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. :)

How to include form submit in countdown

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.

how to make countdoun timer in java script which should not reset on page reload

i have used this code it working but when i refresh the page it reset to initial stage, i want it should continue after page reload also here is code i have used
<html>
<head>
<title>Timer</title>
</head>
<body>
<form name="counter"><input type="text" size="8" name="d2"></form>
<script>
<!--
//
var milisec=0
var seconds=30
document.counter.d2.value='30'
function display()
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
milisec=0
seconds+=1
}
else
milisec-=1
document.counter.d2.value=seconds+"."+milisec
setTimeout("display()",100)
}
display()
-->
</script>
</body>
</html>
You can save current seconds value in localStorage (or maybe sessionStorage) this is the easiest way to persist the value:
var milisec = 0
var seconds = localStorage.seconds || 30;
document.counter.d2.value = seconds;
function display() {
if (milisec <= 0) {
milisec = 9
seconds -= 1
}
if (seconds <= -1) {
milisec = 0
seconds += 1
} else milisec -= 1
localStorage.seconds = seconds;
document.counter.d2.value = seconds + "." + milisec;
if (seconds > 0 || (seconds == 0 && milisec > 0)) {
setTimeout(display, 100);
}
}
display();
Also note, that you probably want to stop interval when timer reaches 0 value, so I added seconds > 0 || (seconds == 0 && milisec > 0) part.
Demo: http://jsfiddle.net/6zL5eL2z/1/

SetInterval not refreshing HTML in Chrome

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>

Categories

Resources