Timer in HTML button (as a resend button to submit form) - javascript

I'm sorry if I have bad in english. I hope you can understand what I mean.
Okay, as simply, I'm going to create a resend button with timer.
This button will be a resend button to submit form. If user access the page, the button doesn't start the timer. When user fill the form and submit it, the timer start running, change the text of button like "You can send after {numofsec} second", and add "disabled" class.
When it reach 0 sec, the button will remove "disabled" class and user could resubmit form.
My problem: This button always run timer when user access the page.
Here it is my code:
let x;
let sec = localStorage.getItem("sec") ? parseInt(localStorage.getItem("sec")) : 10;
let interval = null;
function timer() {
localStorage.setItem("sec", sec);
if (sec > 0) {
localStorage.setItem("timer_status", "started")
$("#btn_resend").prop('disabled', true)
$("#btn_resend").html("Please wait for "+sec+" second");
sec--
} else if (sec === 0) {
localStorage.clear()
localStorage.setItem("timer_status", "stopped")
sec = 10;
$("#btn_resend").prop('disabled', false)
$("#btn_resend").html("Resend");
window.clearInterval(interval)
}
}
window.onload = function () {
<?php if (session()->get("timer_status") == "started") { ?>
x = "started"
localStorage.setItem("timer_status", "started");
<?php } else if (session()->get("timer_status") == "stopped") { ?>
x = "stopped"
<?php } ?>
if (x === "started") {
interval = window.setInterval(timer, 1000);
} else {
window.clearInterval(interval);
}
}
There is a session that sent from Controller. I'm using CodeIgniter 4.
session()->set("timer_status", "started");
My problem: This button always run timer when user access the page.
I have already tried and I got confused for this logic.
I'm new at javascript language. Hope you all can help this problem. Thankyou.

Related

Update page 10 second

I don't know how to say it right, sorry in advance.
I want to make a page of the site js that the page can be updated every 10 seconds, does anyone have an example?
**that the user can refresh the page every 10 seconds**
I want my user on my site to be able to refresh the page once every 10 seconds
You can make button that will show after 10 seconds so user can but also don't have to update.
setTimeout(function(){
let button = document.querySelector('button');
button.style.display = "block";
button.onclick = () => window.location.reload();
}, 10000);
window.onkeydown = (e) => {
if(e.key === 'F5'){
e.preventDefault()
}
}
button {
display:none;
}
<button>Click me</button>
EDIT:
It is impossible to prevent the user from reloading the page, however it is possible to ask if they really want to leave, using this code below, if it after 10 seconds it will not ask if they want to leave, however if it has been less than 10 seconds, it will ask if they want to leave.
var r = 0;
window.onbeforeunload = function() {
if(r == 1) {
return "Are you sure you want to leave?";
}
}
setTimeout(function(){
r = 0;
}, 10000);

How can I log out the user even if they don't respond to JavaScript's "confirm()"?

This was the initial code I was using:
setInterval(function(){
r=confirm("You are about to be logged out! Press cancel if you want to remain logged in.");
if (r == true){
window.location.href = '../logout.php';
}else{
location.reload();
}
},30000);
The confirm dialog awaits action from the user. If the action is "cancel", they remain logged in. If the action is "OK" the are redirected to the logout.php page. The issue is that if the user does not respond, they are not logged out after those elapsed 30 seconds.
Then I thought I may use two time intervals:
setInterval(function(){
window.location.href = '../logout.php';
},60000);
setInterval(function(){
r=confirm("You are about to be logged out! Press cancel if you want to remain logged in.");
if (r == true){
window.location.href = '../logout.php';
}else{
location.reload();
}
},30000);
but since the confirm() method halts the script, the 60000 ms is never realised. Is there a way I can get this to work?
Here is my suggestion
start a timer that logs the user out
start a graceTimer to show a link
if link clicked, the timers restarts
if not, the user is logged out
https://jsfiddle.net/mplungjan/t5ejs72q/
let tId, tId1;
const end = 15000, // change to whatever - 30 minutes
grace = 3000, // 3 secs - should be 30 secs in real life
timer = () => {
clearTimeout(tId);
tId = setTimeout(function() {
// location.replace('../logout.php')
console.log("logged out")
}, end);
},
graceTime = () => tId1 = setTimeout(toggleGrace, end - grace),
toggleGrace = () => document.getElementById("stayLink").classList.toggle("hide"),
init = () => {
timer();
graceTime()
};
document.getElementById("stayLink").addEventListener("click", function(e) {
e.preventDefault();
toggleGrace();
init()
})
init()
.hide {
display: none;
}
Stay logged in?

How to reset recaptcha after user validates and it expires?

Ok so the code I'm trying to figure out so far is this:
function recaptchaCallback() {
$('#submitBtn').removeClass('btn-hide');
$('#submitBtn').addClass('btn-show');
if (grecaptcha.getResponse() == ''){
$('#submitBtn').addClass('btn-hide');
$('#submitBtn').removeClass('btn-show');
grecaptcha.reset();
}
}
What I'd like to do is something like this: if recaptcha = expired then do this {}
if (grecaptcha.getResponse() == ''){
I think is close to what I need, but how do we determine if the recaptcha has expired after the user validated they were human. The recaptcha expires after 60 seconds if a user validates and then doesn't press the submit button. At which point it needs to be revalidated, so it would make sense to disable the submit button when this happens too. Which is what I'm trying to accomplish.
setInterval can wait 60 seconds before executing the code.
function recaptchaCallback() {
$('#submitBtn').removeClass('btn-hide');
$('#submitBtn').addClass('btn-show');
setInterval(function () {
$('#submitBtn').addClass('btn-hide');
$('#submitBtn').removeClass('btn-show');
grecaptcha.reset();
clearInterval(this);
}, 60000);
}
Taking Ty Q.'s solution I noticed it worked, but was continually firing, so it was only working the first time. Once the setInterval was fired even with the clearInterval it kept firing every 60 seconds. I researched on this and came up with this solution.
function recaptchaCallback() {
$('#submitBtn').removeClass('btn-hide');
$('#submitBtn').addClass('btn-show');
var timesRun = 0;
var interval = setInterval(function(){
timesRun += 1;
if(timesRun === 1){
$('#submitBtn').addClass('btn-hide');
$('#submitBtn').removeClass('btn-show');
grecaptcha.reset();
clearInterval(interval);
}
}, 60000);
}

How do it look in Jquery

Hello StackOver Flow friends!
Please I am a newbie
I need to convert this code to Jquery!
I am working on it but unable to make it work. I am learning javascript but I want to see how do the same code work in Jquery. What all I need.
Now, What this function do is:
When an audio starts and as the time limit of 30 sec gets over. It Shows a confirm box whether to login for listening to the audio further or not.
If user clicks 'OK' it redirects to a login page and If the User clicks close or cancel it refreshes the page. Now What I need is that I need to make the confirm box appear with css style. So I need to change it to jquery . Or what the Masters of code think would be perfect.
<script>
document.addEventListener("play", function (e) {
var audios = document.getElementsByTagName("audio");
for (var i = 0, len = audios.length; i < len; i++) {
if (audios[i] === e.target) {
e.target.addEventListener("canplaythrough", function () {
setTimeout(function () {
e.target.pause();
var r = confirm("Please Log in for more than 30s preview!");
if (r == true) {
//x = "You pressed OK!";
window.location.href = "https://www.google.com";
} else {
//x = "You pressed Cancel!";
location.reload();
}
},
30000);
}, false);
}
}
}, true);
</script>

How do I expire a PHP session after sometime when user is not active

i want php session to be expired if there is no activity on the page for more than 10 to 20 minutes. Or user is not available for more than 20 min.Say we are taking an example of login, user logged in and after 20 min if there is no activity , it should expire the session and redirect to login page again.
Use Jquery
html or php page :
<body id="homepage" onload="set_interval()" onmousemove="reset_interval()" onclick="reset_interval()" onkeypress="reset_interval()" onscroll="reset_interval()">
jquery
//user login sessions
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 300000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 300000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
**window.location = "index.php?opt=Logout";**
}
LOGOUT page
if(#$_REQUEST['opt']=='Logout')
{
unset($_SESSION['uid']);
unset($_SESSION['username']);
}
Store the last request made time in session
<?php
$_SESSION['timeout'] = time();
?>
In every request happening, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// destroy session & logout
} else {
$_SESSION['timeout'] = time();
}
?>
The Client-side solution:
Your page:
<script type="text/JavaScript">
var idleRefresh;
idleRefresh = setTimeout("location.href = 'unset.php';",30000);
windows.onmousemove = function() {
clearTimeOut(idleRefresh);
idleRefresh = setTimeout("location.href = 'unset.php';",30000);
};
</script>
unset.php: (Unset all session variables / specific login variables, and redirect user to login page)
<?php
session_unset();
header('Location: login.php');
?>
I would have added this add a comment to Arun's jquery solution, but don't have 50 reputation yet. I had to make some modifications to his code to get it working, for example, this:
timer = setInterval("auto_logout()", 300000);
Needs to be changed to this:
timer = setInterval( function(){ auto_logout() }, 300000);
I have included the fully revised code below:
HTML:
<body onload="setTimer()" onmousemove="resetTimer()" onclick="resetTimer()" onkeypress="resetTimer()" onscroll="resetTimer()">
And Javascript is:
// Variables: timer, timeout
var t, to = 10000;
// Setup the timer
function setTimer() {
t = setInterval( function(){
logout()
}, to);
}
// Reset the timer
function resetTimer() {
if (t > 0) {
clearInterval(t);
setTimer();
}
}
// Logs user out
function logout() {
window.location = "login.php";
}
As Arun has mentioned, change timeout (to) to whatever you need. In the above example I have it set to 10000, which is only 10 seconds.
Hope this helps - and thanks again for Arun for posting the original code.
// JQUERY SCRIPT;
var reset = 60000;
var timer = reset;
$('body').on('click keyup mousemove', function(){
timer=reset;
});
// COUNTDOWN FUNCTION 'ct' SHOW THE TIMING ON YOUR SIGNOUT BUTTON AND
// WILL REDIRECT TO LOGOUT ACTION AFTER THE REACH SET TIMEOUT;
function ct(){
$('#so').text(timer/1000+' Sec. SIGN OUT');
timer=timer-1000;
if(timer==0){
window.location = 'logout.php';
}
}
// EXECUTE 'ct' FUNCTION AFTER EVERY 1 SEC.
setInterval('ct()', 1000);
/* CSS CODE OF SIGNOUT BUTTON */
#so{
background-color: tomato;
padding:8px 20px;
color:#fff;
border-radius: 4px;
text-decoration: none;
}
h3, #so{font-family: Segoe UI;}
<!-- LIBRARY -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- HTML CODE -->
SIGN OUT
<h3>RESET TIMER WITH - MOVE CURSOR, KEY UP & CLICK<h3>

Categories

Resources