How to make a JS function not self-invoke? - javascript

I have issues with the confirm() function. It seems to ignore the setTimeout() function and invokes itself immediately.
I want the function to wait until the 600 seconds is done before invoking.
function stillThere () {
if(confirm("Your session has expired. Are you still here?")){
//Continue
} else{
window.location.href = "../logout.php";
}
}
setTimeout(stillThere, 600);

The timeout parameter for setTimeout is number in milliseconds
function stillThere (){
if(confirm("Your session has expired. Are you still here?")){
//Continue
}else{
window.location.href = "../logout.php";
}
}
// 1 second = 1000 ms
// 600 seconds = 600000 ms
setTimeout(stillThere, 600000);

Related

AJAX request get's called twice because of an interval

I've a problem with my interval function. This is my function:
let data = {
action: "verify_status",
};
let interval = setInterval( function () {
if ( new Date().getTime() - startTime > 600000 ) {
alert( "Error: Timed out!" );
clearInterval( interval );
}
jQuery.post( ajax_url, data, function () {
} ).success( function () {
clearInterval( interval );
successFunction();
} ).fail( function ( response ) {
if ( response.status === 500 ) {
clearInterval( interval );
}
} );
}, 5000 );
My problem is now the following: The interval starts an AJAX request, which now runs in parallel. This is fine as long as the request fails with HTTP 400.
But if it runs successfully, my successFunction() is called. Unfortunately the interval continues running outside. As a result my successFunction() is called twice and sometimes three times, although I interrupt the execution with clearInterval(). Does anyone have an idea how I can do this better?
If you don't want the requests to fire in parallel, then don't use an interval. Instead, use a timeout which only runs once. When the AJAX request completes, set a new timeout to trigger the next one. That's a much better way to ensure that there's no overlap.
Something like this:
setTimeout(runAjax, 5000);
function runAjax()
{
if (new Date().getTime() - startTime > 600000) {
alert( "Error: Timed out!" );
}
jQuery.post(ajax_url, data)
.success(function ()
{
successFunction();
setTimeout(runAjax, 5000);
})
.fail( function ( response ) {
setTimeout(runAjax, 5000);
});
}
You cleared the interval with the name verifyPaymentInterval on success. Try clearing the one with the name "interval" as well.

How to make same function execute different part of the code when called at different intervals

Is this even possible to do? I want to use the same function at different intervals. How can I make the function run at 5000 and execute certain part of code within the function.
here is an example to give an idea:
var moto = function(){
// at 5000 run this part of code
console.log("did stuff when called at 5000 time interval")
// at 6000 run this part of code
console.log("did stuff when called at 6000 time interval")
}
window.setInterval(moto, 5000)
window.setInterval(moto, 6000)
So pass a parameter with the call.
var moto = function( val){
if(val===5000) {
// at 5000 run this part of code
console.log("did stuff when called at 5000 time interval");
} else {
// at 6000 run this part of code
console.log("did stuff when called at 6000 time interval");
}
}
window.setInterval(moto.bind(this, 5000), 5000);
window.setInterval(moto.bind(this, 6000), 6000);
If you really want it to be the same function, set a delay of the greatest common divisor of the desired delays, in this case gcd(5000, 6000) = 1000. And then use a counter.
var counter = 0;
var moto = function() {
++counter;
if (counter % 5 == 0) // at 5000 run this part of code
console.log("did stuff when called at 5000 time interval")
if (counter % 6 == 0) // at 6000 run this part of code
console.log("did stuff when called at 6000 time interval")
};
window.setInterval(moto, 1000);
One way would be pass some param to your functions like:
var moto = function(runAt){
// at 5000 run this part of code
if(runAt==500)
console.log("did stuff when called at 5000 time interval")
// at 6000 run this part of code
if(runAt==600)
console.log("did stuff when called at 6000 time interval")
}
window.setInterval(function() {moto(500)}, 5000)
window.setInterval(function() {moto(600)}, 6000)
Look another way of doing things :P
class Moto {
constructor(delay) {
this.delay = delay
setInterval(this.fn.bind(this), delay)
}
fn() {
// at 5000 run this part of code
if (this.delay === 5000)
console.log("did stuff when called at 5000 time interval")
// at 6000 run this part of code
if (this.delay === 6000)
console.log("did stuff when called at 6000 time interval")
}
}
new Moto(5000)
new Moto(6000)

Retry count and interval

How do I write script If a communication error is received, function shall by default, retry up to 3 times with a 15 second interval between re-tries. Whether a retry on a communication error is performed, the number of retries and the wait interval between tries shall be client configurable parameters. Please help me on this.
You can simply add a variable like FailedCounts and work with it.
Something like:
var failedCounts = 0, myInterval;
myInterval = setInterval(function() {
if (operationFailed) {
failedCounts++;
if (failedCounts >= 3) {
clearInterval(myInterval); // probably, you may want to disable timer on failure
alert('Failed 3 times');
}
} else {
failedCount = 0;
}
}, 15000);

How can you stop polling due to a timeout?

So I'm polling something pretty standard
(function poll(){
$.ajax({ ... })
});
... and it works well. But now, I want to be able to continue polling every couple seconds and then if I don't get a response after two minutes, stop polling and raise an error.
How do I do the timeout?
How about something like this. Init, track, and reset the polling within the ajax promises.
var pollingTimer = null, // stores reference to the current timer id
firstTimeoutResponse = null; // stores the start of what might be a series of timeout responses
function poll(){
$.ajax({
// your options here...
}).done(function() {
// reset the "timeout" timer
firstTimeoutResponse = null;
}).fail(function(jqXHR, textStatus) {
// if the failure wasn't a timeout, short-circuit,
// but only after resetting the timeout timestamp
if (textStatus !== 'timeout') {
firstTimeoutResponse = null;
return;
}
// if it was a timeout failure, and the first one (!), init the timeout count
if (firstTimeoutResponse = null) {
firstTimeoutResponse = (new Date).getTime();
}
}).always(function() {
// if 2 min have passed and we haven't gotten a good response, stop polling/chort-circuit
if ((new Date).getTime() - firstTimeoutResponse > 120000) { // 120000ms = 2min
window.clearTimeout(pollingTimer);
return;
}
// queue the next ajax call
pollingTimer = window.setTimeout(poll, 3000); // poll every 3s
});
}
// kick things off!
poll();

Call javascript function after specific time intervals

I am writing code for JavaScript.In which I am trying to check the remote asp.net page(aspx) connection using AJAX.But also I want to check the condition that, this call will continue for 2 Minute only and with 10 sec time intervals.
not that but like that logic I am thinking,
If flag=true
if seconds < 120
setInterval("GetFeed()", 2000);
can anybody please help me for that.
Here is my code of Connection check,
var learnerUniqueID1;
var flag='true';
function fnCheckConnectivity(coursId)
{
//here will the remote page url
var url = 'http://<%=System.Web.HttpContext.Current.Request.UrlReferrer.Host+System.Web.HttpContext.Current.Request.ApplicationPath%>/TestConn.aspx';
//alert(url);
if (window.XMLHttpRequest) {
learnerUniqueID1 = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
learnerUniqueID1 = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
learnerUniqueID1.open("POST", url, true);
learnerUniqueID1.onreadystatechange = callbackZone;
learnerUniqueID1.send(null);
}
function callbackZone()
{
if (learnerUniqueID1.readyState == 4)
{
if (learnerUniqueID1.status == 200)
{
//update the HTML DOM based on whether or not message is valid
parseMessageZone();
}
else
{
flag='false';
alert('We have detected a break in your web connection, \n please login again to continue with your session');
}
}
}
function parseMessageZone()
{
var result = learnerUniqueID1.responseText;
}
function makePayment(obj)
{
try
{
var Id = obj.attributes["rel"].value
//alert(Id);
var res=confirm('Want to Continue.');
if(res == true)
{
startRequest(Id);
//return true;
}
else
{
return false;
}
}
catch(Error)
{
}
}
function startRequest(Id)
{
var milliseconds = 10000;
currentDate = new Date();
// start request
pollRequest(milliseconds, false, currentDate, 120000,Id);
}
function pollRequest(milliseconds, finshed, date, timeout,Id)
{
if((new Date()).getTime() > date.getTime()+timeout)
{
// 2-minute timeout passed
return;
}
if(!finished){
setTimeout(function(){
if(//check backend to see if finished) //which method will go here
{
fnCheckConnectivity(coursId);
pollRequest(milliseconds, true, date, timeout,Id);
}
else{
pollRequest(milliseconds, false, date, timeout,Id)
}
}, milliseconds);
return;
}
// when code reaches here, request has finished
}
I'm not sure I understand correctly, but if you are trying to poll the status of a request you made every ten seconds, why not try something like this?
function startRequest(){
var milliseconds = 10000;
currentDate = new Date();
timeout = 120000;
// start request
pollRequest(milliseconds, false, currentDate, timeout);
}
function pollRequest(milliseconds, finshed, date, timeout){
if((new Date()).getTime() > date.getTime()+timeout){
// 2-minute timeout passed
return;
}
if(!finished){
setTimeout(function(){
if(//check backend to see if finished){
pollRequest(milliseconds, true, date, timeout);
}
else{
pollRequest(milliseconds, false, date, timeout)
}
}, milliseconds);
return;
}
// when code reaches here, request has finished
}
Please note this is a recursive function and browsers have a recursion limit. Also, regarding the 2 minute timeout, you can either set the timeout as an ajax prefilter or add a variable that is added on each recursion.
If I understand correctly to want to do a task for 2 minutes every 10 seconds.
var interval = setInterval(function(){
// do stuff
},10000); // execute every 10 seconds
setTimeout(function(){
clearInterval(interval);
},120000); // Remove interval after 2 minutes
You don't want a script running continuously on a server/client. You should look up chronjob for linux or scheduler for windows.
I didn't give you a proper solution, just an alternative. For what you seem to want to do, however, this seems like the right tool.
Instead of a push request that you're describing, in which the client user waits for a certain amount of time and then makes a request, you should use a pull request.
To do that, you can make an AJAX call to the sever, and then the sever can wait (and possibly do something else while waiting) and then return something to the user when data is ready.

Categories

Resources