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

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
}

Related

Exit setTimeout loop within AJAX GET request

I have a function that performs an AJAX GET request every 1 second to retrieve data and update a progress bar. I'm using setTimeout to accomplish this. Here is the code:
function check_progress(thread_id) {
function worker() {
$.get('ecab_run/progress/' + thread_id, function(data) {
progress = data['progress'];
status_message = data['status_message'];
if (progress < 100) {
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$('.progress-bar')[0].innerHTML = progress+"%";
$('#status-message')[0].innerHTML = status_message
timer = setTimeout(worker, 1000);
// console.log(timer);
} else if ( progress == 100 ){
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$('.progress-bar')[0].innerHTML = progress+"%";
}
})
return status_message;
}
worker();
}
The function is called after a successful POST as such:
$('#ecab-run-dates').submit(function(e){
e.preventDefault();
var formData = $('form').serialize();
$.ajax({
url:'',
type:'post',
data:formData,
success:function(data){
thread_id = data;
$('.progress-container').show();
check_progress(thread_id);
}
});
});
The backend returns status messages as the behind-the-scenes functions execute, and when it encounters an error, it returns Error: could not compile data or something similar.
My initial thought was to use the error message as a condition for stopping the check_progress function. I've read several answers, including this one that say to use clearTimeout, but I'm not exactly sure how to structure that in my code. Can someone help me exit the setTimeout loop when encountering an error?

How to continue calling getjson untill it has no empty response?

Hi all i got a getjson call and wondering how i can check its response(siteContents) if it is empty or if it doesn't have a required string(for example look for seasonEpisode=)then call getjson again .Can we call getjson itself from within it ?My goal is to get correct response from getjson.Hope you guys help me.Thanks
$.getJSON('http://www.mysite.com/doit.php?value=55?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
Try this:
var handler = function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
if (!siteContents) {
$.getJSON('http:/...', handler);
return;
}
// handle siteContents
}
$.getJSON('http://...', handler);
edit: the above would spam the server with repeating attempts in case the siteContents is empty - creating infinite loop and high load. I would suggest two improvements:
1) count how many repeating empty siteContents loops you made. Cancel the loop with an error message (if appropriate) after some failure threshold (eg. 20 attempts).
2) do the iteration with setTimeout(function() { $.getJSON(...) }, delay) where delay is some milliseconds to wait between retries.
It sounds like the better question is why doesn't your server return the 'correct' response on the first try? Or as NuclearGhost points out, why does it return different responses for the same request?
But to accomplish what you're asking for requires recursion. You can't just do it in a loop because the response is asynchronous. But if you name a function, you can call that function in the success handler, something like this:
function getJSONRecursive(maxRetries, count) {
if(!count) count = 1;
if (count > maxRetries) {
alert('Giving up after '+count+' retries.');
return;
}
$.getJSON('http://www.mysite.com/doit.php?', function(data) {
if(!data || !data.contents || data.contents.indexOf('seasonEpisode') == -1) {
getJSONRecursive(++count, maxRetries);
} else {
$('#output').html(data.contents);
}
})
}
Then invoke it like this:
getJSONRecursive(5);
I wouldn't recommend doing without the count, because otherwise you will overflow the stack if the correct response never comes back. If the situation you're avoiding is a server timeout or overload problem, then I would recommend putting the recursive call in a timeout, like so:
if(!data || !data.contents || data.contents.indexOf('seasonEpisode') == -1) {
setTimeout(function() { getJSONRecursive(++count, maxRetries)}, 5000);
// etc.
This waits an extra 5 seconds between calls, but the extra time will help ensure your server doesn't get slammed and your getjson calls don't just run themselves out too quickly.

Javascript recursive setTimeout doesn't use full final JSON returned

I am making recursive calls to a URL until it returns success or has hit the max tries limit. Here is the relevant code, (minified, so to speak):
function doSomething(numRetries) {
$.post('someURL', {retry: numRetries},
function (data) {
if (data.value == 1) {
displayResults(data.message, data.value);
} else if (data.value == "retry") {
setTimeout( function() { doSomething(data.retries) }, 1000);
} else {
displayResults(data.message, data.value);
}
},
"json"
);
}
IFF the first call to sumeURL returns data.value == 1, it executes displaySuccess. Similarly, if it returns another value (e.g. 0), it will displayFailure() successfully.
The problem lies in the recursive part. After it kicks off the retries, it does call doSomething() again with an incrementing retries value, but any return data after that is not used.
So when my retry timeout inside someURL is 3, for example, I can see in firebug:
post('someURL', 0) returns JSONified (value = "retry", retries = 1)
post('someURL', 1) returns JSONified (value = "retry", retries = 2)
post('someURL', 2) returns JSONified (value = 0, error = "Display this error!")
but an alert() inside displayFailure indicates that error = [undefined], even though value = 0 (not "retry"). Firebug indicates proper JSON parsing is occurring.
EDIT modify the doSomething to be a more accurate reflection of reality, though the changes shouldn't introduce any uncertainty, and by request, here are the actual return values from the post calls:
{"success":"retry","retryCount":"1"}
{"success":"retry","retryCount":"2"}
{"success":0,"errormsg":"The request is taking longer than expected, but should be completed soon. Please try again in 15 minutes."}
and lastly here is a minified displayResults():
function displayResults(text, status) {
$('#dispElem').queue(function(next) { //this is so that fades happen around the text update, not before/during it; there may be better ways to do this
$('#dispElem').html(text);
if (status == 1) {
$('#dispElem').addClass("success");
} else {
// hide and show random elements
}
next();
}).fadeIn().queue(function(next) { //scroll to bottom; next(); });
}
Arrrgh.
The worst scenario of all - an uppercase/lowercase mistake I just kept overlooking until forced to retype to minify.
Thanks, all, for the comments and making me recomb it, with a finer tooth, so to speak.

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.

jQuery AJAX polling for JSON response, handling based on AJAX result or JSON content

I'm a novice-to-intermediate JavaScript/jQuery programmer, so concrete/executable examples would be very much appreciated.
My project requires using AJAX to poll a URL that returns JSON containing either content to be added to the DOM, or a message { "status" : "pending" } that indicates that the backend is still working on generating a JSON response with the content. The idea is that the first request to the URL triggers the backend to start building a JSON response (which is then cached), and subsequent calls check to see if this JSON is ready (in which case it's provided).
In my script, I need to poll this URL at 15-second intervals up to 1:30 mins., and do the following:
If the AJAX request results in an error, terminate the script.
If the AJAX request results in success, and the JSON content contains { "status" : "pending" }, continue polling.
If the AJAX request results in success, and the JSON content contains usable content (i.e. any valid response other than { "status" : "pending" }), then display that content, stop polling and terminate the script.
I've tried a few approaches with limited success, but I get the sense that they're all messier than they need to be. Here's a skeletal function I've used with success to make a single AJAX request at a time, which does its job if I get usable content from the JSON response:
// make the AJAX request
function ajax_request() {
$.ajax({
url: JSON_URL, // JSON_URL is a global variable
dataType: 'json',
error: function(xhr_data) {
// terminate the script
},
success: function(xhr_data) {
if (xhr_data.status == 'pending') {
// continue polling
} else {
success(xhr_data);
}
},
contentType: 'application/json'
});
}
However, this function currently does nothing unless it receives a valid JSON response containing usable content.
I'm not sure what to do on the lines that are just comments. I suspect that another function should handle the polling, and call ajax_request() as needed, but I don't know the most elegant way for ajax_request() to communicate its results back to the polling function so that it can respond appropriately.
Any help is very much appreciated! Please let me know if I can provide any more information. Thanks!
You could use a simple timeout to recursively call ajax_request.
success: function(xhr_data) {
console.log(xhr_data);
if (xhr_data.status == 'pending') {
setTimeout(function() { ajax_request(); }, 15000); // wait 15 seconds than call ajax request again
} else {
success(xhr_data);
}
}
Stick a counter check around that line and you've got a max number of polls.
if (xhr_data.status == 'pending') {
if (cnt < 6) {
cnt++;
setTimeout(function() { ajax_request(); }, 15000); // wait 15 seconds than call ajax request again
}
}
You don't need to do anything in your error function unless you want to put an alert up or something. the simple fact that it error will prevent the success function from being called and possibly triggering another poll.
thank you very much for the function. It is a little bit buggy, but here is the fix. roosteronacid's answer doesn't stop after reaching the 100%, because there is wrong usage of the clearInterval function.
Here is a working function:
$(function ()
{
var statusElement = $("#status");
// this function will run each 1000 ms until stopped with clearInterval()
var i = setInterval(function ()
{
$.ajax(
{
success: function (json)
{
// progress from 1-100
statusElement.text(json.progress + "%");
// when the worker process is done (reached 100%), stop execution
if (json.progress == 100) clearInterval(i);
},
error: function ()
{
// on error, stop execution
clearInterval(i);
}
});
}, 1000);
});
The clearInterval() function is becomming the interval id as parameter and then everything is fine ;-)
Cheers
Nik
Off the top of my head:
$(function ()
{
// reference cache to speed up the process of querying for the status element
var statusElement = $("#status");
// this function will run each 1000 ms until stopped with clearInterval()
var i = setInterval(function ()
{
$.ajax(
{
success: function (json)
{
// progress from 1-100
statusElement.text(json.progress + "%");
// when the worker process is done (reached 100%), stop execution
if (json.progress == 100) i.clearInterval();
},
error: function ()
{
// on error, stop execution
i.clearInterval();
}
});
}, 1000);
});
You can use javascript setInterval function to load the contents each and every 5 sec.
var auto= $('#content'), refreshed_content;
refreshed_content = setInterval(function(){
auto.fadeOut('slow').load("result.php).fadeIn("slow");},
3000);
For your reference-
Auto refresh div content every 3 sec

Categories

Resources