How to include form submit in countdown - javascript

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.

Related

How to stop the setTimeout counter from another function call through button click

I am creating an sample application, user signout time is 15 minutes.
Before 2 minute, users gets an pop with warning message with countdown.
There are two buttons.
Logout => for logout.
StayLogin => get additional 15 minutes time into the application.
For the first time , when user reaches 13 minutes, gets the popup.
So when click the proceed button, logout time gets added .
Problem :
The problem with the counter. If counter reaches 0 seconds 0 minutes it have redirect to login page.
In between the counter, user clicked, added another 15 minutes, but timer reaches 0 seconds and go to the login page.
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) {
$state.go("root"); // problem
}
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
if (mins > 1) {
alert('minutes');
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function() {
countdown(mins - 1);
}, 1000);
}
}
}
tick();
}
countdown(1); * *
// staylogin
$rootScope.proceed = function() {
var lastDigestRun = Date.now();
var s = lastDigestRun + 3 * 60 * 1000;
var displaytime = now - lastDigestRun > 3 * 60 * 1000;
if (now - lastDigestRun > 2 * 60 * 1000) {
clearTimeout(tick);
load();
}
}
How to stop the counter when click the stayLogin button?
You need to use something like
$timeout.cancel(timer)
to cancel the timer and recreate a new one.
Have a look at how I would do it below.
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope, $timeout, $interval) {
$scope.name = 'MyConfusedUser';
$scope.firstLoad = true;
$scope.loggingOut = false;
$scope.loggOutIn = 5;
$scope.loggingOutIn = 10;
$scope.maxLoginTime = 10;
$scope.getTimer = function(seconds){
return $timeout(function(){
alert('you are logged out');
}, seconds * 1000);
}
$scope.resetTime = function(){
$timeout.cancel($scope.currentTimer);
$scope.currentTimer = $scope.getTimer($scope.maxLoginTime);
$scope.loggingOutIn = $scope.maxLoginTime;
$scope.loggingOut = false;
}
if($scope.firstLoad){
$scope.firstLoad = false;
$interval(function(){
$scope.loggingOutIn--;
if($scope.loggingOutIn < $scope.loggOutIn){
$scope.loggingOut = true;
}
}, 1000, 0);
$scope.timers = [];
$scope.currentTimer = $scope.getTimer($scope.maxLoginTime);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="MainCtrl">
<div ng-hide="loggingOut">
<p>Hello {{name}}!</p>
</div>
<div ng-show="loggingOut">
<p>{{name}}, you will be logged out very soon.</p>
</div>
<p>Logging out in {{loggingOutIn}} seconds</p>
<p ng-show="loggingOut"><button ng-click="resetTime()">Reset Time</button></p>
</body>
You need to pass clearTimeout a variable that references the setTimeout, rather than the callback function. e.g.
var to = setTimeout(function(){...});
clearTimeout(to);
Why not return the setTimeout form your tick function?

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 restart javascript function using jquery issue

Hello I have a timer that executes via php/html like this
// timer
print "<script>countdown();</script>";
However I have a jquery warning dialog that looks like this, I would like for the javascript function to restart after they click the close button
// Create timeout warning dialog
$('body').append('<div title="Timeout"</div>');
$('#sessionTimeout-dialog').dialog({
autoOpen: false,
width: 600,
modal: true,
closeOnEscape: false,
open: function(event, ui) { $(".dialog").hide(); },
buttons: {
// Button two - closes dialog and makes call to keep-alive URL
"Continue Session": function() {
$(this).dialog('close');
clearTime();
$.ajax({
type: 'POST',
url: o.keepAliveUrl
});
countdown(); //I call the javascript function in hopes of making it go again
}
}
});
However I cant seem to make the timer actually restart once the button is click to continue. here is my timer code, what I'am I doing wrong? I call the javascript function after the button is closed but nothing happens it just goes to a negative number
// set minutes
var mins = 2;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
It looks like your countdown function doesn't reset the timer, but only starts the decrement loop.
Add something like
function resetCountdown()
{
secs = mins * 2;
}
and call this function when the dialog is closed to reset the countdown. Do NOT call countdown() again as this will create another timer in addition to the already running one.
Also there is an error in your code:
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
should be
if (secs < 59) {
minutes.value = 0;
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
I'm not completely sure this is what you want, but:
I like to restart certain timers when the window regains focus(from the dialog). Below is an example:
<html>
<head>
<script>
g = {};
g.timer = false;
g.count = false;
g.waittime = 3; //seconds for timer.
g.timeleft = (g.waittime * 100) - 10;
checktimer = function(){
if(g.timer === false){
g.timer = setTimeout(function(){
g.timer = false;
g.timeleft = g.waittime * 100;
alert("Hi!");
},g.waittime * 1000);
}
if(g.count === false){
g.count = setInterval(function(){
g.timeleft-=10;
document.getElementById("disp").innerText =(g.timeleft/100).toString().match(/^\d+(?:\.\d{0,2})?/);
},100);
}
}
window.onfocus = function() {
checktimer();
};
</script>
</head>
<body onload="checktimer();">
<div>Time Left: <span id="disp">0</span> Seconds.</div>
</body>
</html>

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>

Countdown timer on Label for 30 seconds using 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>

Categories

Resources