Retry count and interval - javascript

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);

Related

javascript 'setTimeout' function stops running after 6 minutes on Flask web server

*edit: I found a bug in Celery task which leads to this problem. So it's unrelated to that piece of JavaScript code blow. Suggest to close this question.
I have this Javascript function running on Flask web server, which checks status of a Celery task. If the task finished, console.log its result, otherwise recheck after 2 seconds.
It runs well if the Celery task finished in less than 6 minutes. However, when it hits the 6 minute mark, this function just stops running. The status of Celery task never updated again, even though I am sure that task is still running on the background, I don't receive any result from Javascript.
Is it a timeout setting of Flask? Any insights will be appreciated.
function update_progress(status_url) {
// send GET request to status URL
$.getJSON(status_url, function(data) {
if (data['state'] != 'PROGRESS') {
if ('result' in data) {
console.log(data['result']);
}
else {
// something unexpected happened
console.log(data['state']);
}
}
else {
// rerun in 2 seconds
setTimeout(function() {
update_progress(status_url);
}, 2000);
}
});
}
you could try use setInterval instead, registering it to a variable.
const updateInterval = setInterval(function(){
update_progress(status_url);
},2000);
And inside update_progress function, remove the else part and add clearInterval(updateInterval):
function update_progress(status_url) {
// send GET request to status URL
$.getJSON(status_url, function(data) {
if (data['state'] == 'PROGRESS') {
return;
}
clearInterval(updateInterval);
if ('result' in data) {
console.log(data['result']);
}
else {
// something unexpected happened
console.log(data['state']);
}
});
}

Clear a Javascript Interval

I am running a HTTP Request to a file and depending on the response whether it be "200" or another response a success or error function is ran. This request takes place every second.
The problem I am facing is when I get lots of error responses they all run together and the last one doesn't stop e.g. End the interval to start a new one.
The red light begins to flash way too fast. Can anyone help me out. My code is below and I have been playing with it for a few hours now but can't seem to get to the bottom of it.
var requestResponses = {
greenLight: $('.cp_trafficLight_Light--greenDimmed'),
redLight: $('.cp_trafficLight_Light--redDimmed'),
greenBright: 'cp_trafficLight_Light--greenBright',
redBright: 'cp_trafficLight_Light--redBright',
init: function (url) {
setInterval(function () {
requestResponses.getResponse(url);
}, 1000);
},
successResponse: function () {
var redBright = requestResponses.redBright,
greenBright = requestResponses.greenBright;
requestResponses.errorCode = false;
requestResponses.redLight.removeClass(redBright);
requestResponses.greenLight.addClass(greenBright);
},
errorResponse: function () {
requestResponses.runOnInterval();
},
runOnInterval: function () {
// clearInterval(runInterval);
var redBright = requestResponses.redBright,
greenBright = requestResponses.greenBright,
redLight = requestResponses.redLight;
requestResponses.greenLight.removeClass(greenBright);
var runInterval = setInterval(function () {
if (requestResponses.errorCode === true) {
redLight.toggleClass(redBright);
}
}, 400);
},
getResponse: function (serverURL) {
$.ajax(serverURL, {
success: function () {
requestResponses.errorCode = false;
requestResponses.successResponse();
},
error: function () {
requestResponses.errorCode = true;
requestResponses.errorResponse();
},
});
},
errorCode: false
}
requestResponses.init('/status');
Appreciate the help.
Javascript is an event driven language. Do not loop inifinitely to check things periodically. There are places to do so but most of the time either calling a delay function (setTimeout) repeatedly when needed or using a callback would be better method.
Using setInterval with request, think what happens if requests start taking longer than your interval.
In your case, you have two loops created with setInterval. First one is the request which will run every 1 sec. Instead of using setInterval, you can modify your code to run setTimeout only after a request finishes and do other tasks just before re-running the next request :
function runRequest(...) {
$.ajax(serverURL, {
...
complete: function () {
setTimeout(runRequest, 1000);
}
...
});
}
function lightsOnOff() {
var redBright = requestResponses.redBright,
greenBright = requestResponses.greenBright,
redLight = requestResponses.redLight;
requestResponses.greenLight.removeClass(greenBright);
if (requestResponses.errorCode === true) {
redLight.toggleClass(redBright);
}
}
setInterval(lightsOnOff, 400);
The setInterval() method repeats itself over and over, not just one time. Your error response handler is then invoking the routine that creates another setInterval(), and so on. Until you have so many processes running that you get the flashing red light issue.
The solution is to only invoke the logic where the setInterval() call is made once. Or, even better, use setTimeout() to call the routine. It is run one-time and likely better for your use.

setInterval() loop still running after clearInterval() is called

I know that setInterval() returns a unique ID on every loop, and that clearInterval must be called with that ID to kill the loop. I believe my code does this, yet the loop continues to run indefinitely.
var refresh = setInterval(function () {
$.get(url, function (data) {
success: {
if (data < 5) {
data = 5;
}
var width = data + "%";
$("#recalculation-progress-bar").css('width', width);
if (data > 99) {
clearInterval(refresh);
$("#recalculation-message").text("Recalculation complete.");
}
}
});
}, 3000);
I have checked this in debug and clearInterval() is definitely being called and no errors are thrown. Am I doing something obviously wrong?
1.-
data in $.get is a String by default
https://api.jquery.com/jquery.get/
data = parseInt(data)
2.-
You add a second level of sync... Are you sure that this request is faster than 3000ms?
3.- If the data is > 99, the code works.
In my concern, the problem is the request is longer than 3 seconds, and you still receive connections that your previously launched.
if (data > 99) {
clearInterval(refresh);
$("#recalculation-message").text("Recalculation complete.");
} else {
//relaunch here the connection and remove the interval
}

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.

JQUERY AJAX ---- Pausing for usability reasons but only when nessesary?

I have a LoadingStatus Function that has two options SHOW or HIDE.
The Show triggers to display when the JQUERY POST is made, the HIDE happens after the RESPONSE comes back.
The issue I'm having is that sometimes this happens so fast that it makes for a bad experience. What I thought about doing was putting in a JavaScript PAUSE, but if the POST takes a while to respond it will take even longer because of the PAUSE.
How can I have my SHOW HIDE function work together, to make sure at minimum the SHOW was displayed to the user for at least 1/2 second?
function saveBanner (action) {
if (action == 'show') {
// Display the AJAX Status MSG
$("#ajaxstatus").css("display","block");
$("#msg").text('Saving...');
}
else if (action == 'hide') {
$("#ajaxstatus").css("display","none");
$("#msg").text('');
}
};
Thanks
In your ajax success callback, you can put the hide command in a setTimeout() for 1500 miliseconds:
success: function(results) {
setTimeout(function(){
saveBanner("hide");
}, 1500);
}
Of course that would merely add 1.5 seconds onto however long the process itself took. Another solution would be to record the time the process started, with the Date object. Then, when the callback takes place, record that time and find the difference. If it's less than a second and a half, set the timeout for the difference.
/* untested */
var start = new Date();
success: function(results) {
var stop = new Date();
var difference = stop.getTime() - start.getTime();
difference = (difference > 1500) ? difference : 1500 ;
setTimeout(function(){
saveBanner("hide");
}, difference);
}
You can perform this math either inside your callback, or within the saveBanner() function itself, within the show portion you would set the starting time, within the hide() portion you would check the difference and set the setTimeout().
You can use setTimeout/clearTimeout to only show the status when the response takes longer than a set amount of time to load.
Edit:
Some untested code:
var t_id = 0;
function on_request_start()
{
t_id = setTimeout(show_message, 1000);
}
function on_request_completed()
{
clearTimeout(t_id);
hide_message();
}
The JQuery handlers should look something like the above. The message will not be shown if you receive a reply in less than a second.
var shownTime;
function saveBanner (action) {
if (action == 'show') {
// Display the AJAX Status MSG
$("#ajaxstatus").css("display","block");
$("#msg").text('Saving...');
shownTime = new Date().getTime();
}
else if (action == 'hide') {
var hideIt = function() {
$("#ajaxstatus").css("display","none");
$("#msg").text('');
};
var timeRemaining = new Date().getTime() - shownTime - 1500;
if (timeRemaining > 0) {
setTimeout(hideIt, timeRemaining);
else {
hideIt();
}
}
};
As of jQuery 1.5, you are able to extend the $.ajax functionality by using prefilters. I wanted a similar experience where a message was shown a minimum amount of time when an ajax call is made.
By using prefilters, I can now add a property to the ajax call named "delayedSuccess" and pass it a time in milliseconds. The time that is passed in is the minimum amount of time the ajax call will wait to call the success function. For instance, if you passed in 3000 (3 seconds) and the actual ajax call took 1.3 seconds, the success function would be delayed 1.7 seconds. If the original ajax call lasted more than 3 seconds, the success function would be called immediately.
Here is how I achieved that with an ajax prefilter.
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (originalOptions.delaySuccess && $.isFunction(originalOptions.success)) {
var start, stop;
options.beforeSend = function () {
start = new Date().getTime();
if ($.isFunction(originalOptions.beforeSend))
originalOptions.beforeSend();
};
options.success = function (response) {
var that = this, args = arguments;
stop = new Date().getTime();
function applySuccess() {
originalOptions.success.apply(that, args);
}
var difference = originalOptions.delaySuccess - (stop - start);
if (difference > 0)
setTimeout(applySuccess, difference);
else
applySuccess();
};
}
});
I first check to see if the delaySuccess and success options are set. If they are, I then override the beforeSend callback in order set the start variable to the current time. I then override the success function to grab the time after the ajax call has finish and subtract the difference from the original delaySuccess time. Finally, a timeout is set to the computed time which then calls the original success function.
I found this to be a nice way to achieve this effect and it can easily be used multiple times throughout a site.

Categories

Resources