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);
}
Related
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.
Sorry this is going to take a bit of explaining so you know what I'm trying to do here...
I'm having trouble with a timer function. Basically when the user hits the page, an Ajax request is made, the result of which starts a timer function. They have a certain amount of time in which to make a payment (this is a block chain based payment app, payment is made via an external wallet - no user input is required on the payment page at all, no buttons to click etc). If the timer runs out the payment box resets.
But if the persistent Ajax calls running in the background find the users payment on the block chain I need to kill the timer as it is no longer required, but I need to keep the payment box open while the confirmations are being monitored until the transaction is complete.
The trouble is I can't alter the already running timer function. I've tried every way possible I could think of but nothing stops the original function from running and ultimately resetting the payment box while the transaction is ongoing (waiting for confirmations).
I have been reading about wrapping the timer function in an object and adding a listener but everything I found seemed really confusing to me.
Below is the relevant code.
The function that starts the timer is being started by the Ajax response from another function...
myTimer(expiry);
The expiry variable being passed is vital as it sets an intial on / off state for the timer (whether to display it or not from the first response). So I need to keep that.
This is the timer function...
function myTimer(expiry) {
// If expiry set to 0 don't use the timer
if (expiry === 0) {
$('#timer').hide();
return;
}
var start = new Date();
var timeoutVal = Math.floor(expiry/100);
animateUpdate();
function updateProgress(percentage) {
$('#timerInner').css("width", percentage + "%");
}
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
var perc = Math.round((timeDiff/expiry)*100);
if (perc <= 100) {
updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
} else {
// Timer expired, clear box and show buy button again
$("#paymentWrap").empty();
$("#btn-Pay").show();
$("#btn-Pay").prop("disabled", false);
return;
}
}
}
}
This is the part that I need to "kill" on demand via another function coming from another Ajax response...
// Timer expired, clear box and show buy button again
$("#paymentWrap").empty();
$("#btn-Pay").show();
$("#btn-Pay").prop("disabled", false);
return;
Can somebody explain how I can add a variable listener to this function (maybe by creating it as an object?) so that I can change the chunk of code that triggers the bit above to include a new var called cancelled that can be updated elsewhere in the script WHILE this function is running.
if (perc <= 100) {
updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
if (cancelled === true) {
// Hide the timer div and kill the timer function
$("#timer").hide();
return;
}
} else {
// Timer expired, clear box and show buy button again
.......
I know this was really long winded, apologies upfront, but thanks for reading and looking forward to any help you can offer.
Cheers!
You can define a global variable to reference setTimeout() call and use cleaTimeout()
let timer = null;
let then_ = new Date().getTime() + 10000;
function fn() {
timer = setTimeout(function() {
console.log("doing stuff at " + new Date()
, "time remaining to do stuff:", then_ - new Date().getTime());
if (new Date().getTime() < then_) {
fn()
} else {
done()
}
}, 1000)
}
function done() {
clearTimeout(timer);
timer = null;
console.log("done doing stuff at " + new Date());
}
document.querySelector("button")
.onclick = function() {
if (timer) {
done()
} else {
this.onclick = null;
}
}
fn();
<button>clear timer</button>
Below is the function use to check for the session of my page. The page will reload after I clicked the alert message.
var timeleft = 60;
function checkTime() {
timeLeft--;
if (timeLeft == 30 )
{
alert("30 secs left.");
window.location.reload();
}
}
Is there anyway that the timeleft continue minus (if the user din't not notice the alert message) so that it will redirect to logout page when the timeleft is = 0.
alert() is a modal, it stops javascript execution. Check this code:
var start = new Date();
var start2;
window.setTimeout(function() {
var end = new Date();
var result = "time from start: " + (end.getTime() - start.getTime())
result += "\ntime from alert: " + (end.getTime() - start2.getTime())
result += "\nalert was open for: " + (start2.getTime() - start.getTime())
alert(result);
}, 500);
window.setTimeout(function() {
alert("hello");
start2 = new Date();
}, 100);
Fiddle for upper code: http://jsfiddle.net/aorcsik/vfeH2/1/
Check out this code, it shows that even setTimeout is stopped during alert(), but you can check how much time the user was looking at the alert, and update your counter (timeLeft) by decreasing with the measured time devided by your ticker delay.
Solution: So my solution would be to measure how much time the user looks at the alert modal, and whenever he clicks ok, check if his session ended, if yes redirect to logout, else do the usual redirect.
var start = new Date();
alert("xxx");
var t = (new Date()).getDate() - start.getDate();
if (t / 1000 > timeLeft) {
/* logout */
} else {
/* redirect */
}
Note: another solution would be to use some html popup instead of the javascript alert, which would not block javascript execution
If you want an async alert you can try this
setTimeout(function() { alert('30 secs left'); }, 1);
But if you want a timed logout you can do something like this instead:
function checkTime() {
setInterval(function(){alert("30 secs left.")},30000); // shown at 30 seconds
setInterval(function(){logout()},60000); // called at 60 seconds
}
function logout() {
// logout functionality
}
your code comment is strange
first you are using a number (60) and you consider it as (two minutes) then alert it is(30 seconds left)..
Anyways ..
you want to count down and when there is only 30 seconds left you want to reload the page!!
the problem here is that when you reload the page you will reset the count down from (60 as in your code)
the solution is one of the following:
1- save the countdown in localstorage as pointed out by #Fabrizio and when the page is reloaded again then use the saved counterdown value.
however this solution assume that your user browser can save to localstorage
2- second solution is that you post your page with the countdown and reload it with the count down..
let us say that you page address is: www.myexampleaddress.com/mypage
then you call the address as follow :www.myexampleaddress.com/mypage?timeleft=30
and catch this on the server and reload the page from the server with value in your querystring ..
so your coude after the alert should be like this
var myURL = location.href+'?timeleft=30';
location.href =myURL;
i hope that help :)
Ok coming straight to the point
I have a text box and few other things on a page
if the user is typing in the textbox the page should not refresh otherwise it should refresh after a certain interval
I searched alot and cannot find anything similar
I am new to javascript
Here is a simple example of this. A check runs every 3 seconds. if nothing has been typed in it will refresh, if something has been typed in it will wait 3 seconds before refreshing.
http://jsfiddle.net/9ARrG/
HTML
<input onkeyup="resetTimer = true">
JS
resetTimer = false;
setInterval(function() {
if(!resetTimer) {
location.reload();
}
resetTimer = false;
}, 3000);
Give your input/textarea an id
<input id="textbox" />
// OR
<textarea id="textbox"></textarea>
Then, setup a timer to refresh the page. If there's a change, reset the timer.
var originalTimer = 15000; // here's the original time until page refreshes
var timer = originalTimer; // timer to track whether to refresh page
// now every 1 second, update the timer
setInterval(function() {
timer -= 1000; // timer has gone down 1 sec
// if timer is less than 0, refresh page
if (timer <= 0) window.location.reload();
},1000); // repeat every 1 second (1000 ms)
document.getElementById("textbox").onchange = function() {
// detect textbox changes, reset timer
timer = originalTimer;
}
Use the document.activeElement property to conditionally determine what element has focus.
function refreshPageUnlessFocusedOn (el) {
setInterval(function () {
if(el !== document.activeElement) {
document.location.reload();
}
}, 3000)
}
refreshPageUnlessFocusedOn(document.querySelector('textarea'));
Check out the jsfiddle here for a working sample.
I have an unusual problem. I'm using the following script to check for internet connection using navigator.onLine. If there is internet connection, the page will be refreshed every 15 seconds. If there isn't any internet connection, the page will use innerHTML to display a message.
<script type="text/javascript">
setInterval(function () {
if (navigator.onLine) {
var myInterval = setInterval(function(){window.location.href = "Tracker.html";},15000);
} else {
clearInterval(myInterval);
var changeMe = document.getElementById("change");
change.innerHTML = "<big><font face='Arial' color='#ffffff' size='2'><center>OFFLINE</big><br>No internet connection</font></center>";
}
}, 250);
</script>
My problem is, once there is no internet connection, the message will be displayed, BUT the page would still be refreshed one last time. I'm trying to avoid this, by using clearInterval(myInterval); in the else part of the code, however it won't work.
Any suggestions?
To refresh the page at 15 second intervals (provided that a connection is present), use:
function refresh() {
if(navigator.onLine)
window.location.href = "Tracker.html";
else{
var changeMe = document.getElementById("change");
change.innerHTML = "<big><font face='Arial' color='#ffffff' size='2'><center>OFFLINE</big><br>No internet connection</font></center>";
setTimeout(refresh, 250);
}
}
setTimeout(refresh, 15000);
At the end of 15 seconds, this checks whether a connection is present. If there is, it refreshes the page. If there isn't, it proceeds to check every 250 milliseconds afterwards until the user is reconnected, at which point it refreshes the page.
The net result is that the script refreshes the page as soon as possible after a minimum of 15 seconds have elapsed.
Here is a demonstration: http://jsfiddle.net/JGEt9/show
Whenever the outer interval callback is executed, a new myInterval variable is created and the previous one is lost (it goes out of scope because the callback terminates).
You have to persist the value of the variable between function calls by declaring it outside of the function. You also have to make sure that you are not creating another timeout if one is already running.
var timeout = null;
setInterval(function () {
if (navigator.onLine) {
if (timeout === null) {
timeout = setInterval(function(){window.location.href = "Tracker.html";},15000);
}
} else {
clearTimeout(timeout);
timeout = null;
// ...
}
}, 250);
You need to declare myInterval outside of the if statement. You should only need the refresh code once too. Something like this:
var myInterval = setTimeout(function(){window.location.href = "Tracker.html";},15000);
setInterval(function () {
if (!navigator.onLine) {
clearTimeout(myInterval);
var changeMe = document.getElementById("change");
changeMe.innerHTML = "<big><font face='Arial' color='#ffffff' size='2'><center>OFFLINE</big><br>No internet connection</font></center>";
}
}, 250);
Here you set the refresh interval and continually check to see if the browser is offline, and if it is, you remove the timer and do your cleanup code. I also changed the refresh code to use setTimeout instead of interval because it only happens once.
Another issue is you create changeMe but then try to use change. change doesn't exist. I fixed that in my example as well.
Note: This will not resume refreshing once connection is regained. See Felix Kling's answer.