(function poll() {
$.ajax({
url: "/Home/Tail", success: function (data) {
console.log(data);
},
data: { datetime: getISODateTime(new Date()) },
dataType: "json",
timeout: 30000
});
})();
I have the above code, i am doing long polling to an endpoint.
However, it is too fast. Isnt it supposed to do it every timeout seconds?
However, it is too fast. Isnt it supposed to do it every timeout
seconds?
timeout property here will only timeout the call and then fire the error. If you find it too fast, you must be doing something else besides the code posted above.
In order to do a long-polling one way could be to use Javascript setTimeout when you receive a response. Also, in such cases you should have an abort figured out somewhere.
For example (this will poll every 3 seconds):
<button id="start">Start</button>
<button id="stop">Stop</button>
var timer;
function poll() {
$.ajax({
url: "/echo/json/", success: function (data) {
console.log(data);
timer = setTimeout(poll, 3000);
},
data: { datetime: new Date()},
dataType: "json",
timeout: 30000
});
};
$("#start").on("click", function() { console.log("started.."); poll(); });
$("#stop").on("click", function() { console.log("stopped.."); clearTimeout(timer); });
Fiddle: http://jsfiddle.net/abhitalks/rf0uaaLj/
You could use the timeout setting in the ajax options like this:
(function poll() {
$.ajax({
url: "/Home/Tail", success: function (data) {
console.log(data);
},
timeout: 30000,
data: { datetime: getISODateTime(new Date()) },
dataType: "json"
});
})();
Read all about the ajax options here
Related
$.ajax({
url: vars.url,
type: "post",
data: r,
async: true,
processData: vars.process,
contentType: vars.contenttype,
beforeSend: function(){
if(vars.loadbar == 'true'){
setInterval(function () {
$.getJSON(domain + '/core/files/results.json', function (data) {
console.log(data);
})
}, 1000);
}
},
complete: function(){
clearInterval();
},
succes: function(data){
..................
}
})
So I am trying to end the infinite loop my code is spawning as soon as my ajax call is being done. It now phones pretty much every second to my file to get results, which i want to stop as soon as my ajax call is completed.
I am not sure how to approach this, since if i assign a variable to the setInterval (being it in the function of the beforeSend itself, or outside of the AJAX call), it either wont see the variable, or my variable is empty. I think I am approaching this wrong. Can I check within the beforeSend if the AJAX call is complete to end the loop?
you can store your interval as a global variable and clear it when you need it. like so:
let interval;
$.ajax({
url: vars.url,
type: "post",
data: r,
async: true,
processData: vars.process,
contentType: vars.contenttype,
beforeSend: function(){
if(vars.loadbar == 'true'){
interval = setInterval(function () {
$.getJSON(domain + '/core/files/results.json', function (data) {
console.log(data);
})
}, 1000);
}
},
complete: function(){
clearInterval(interval);
},
succes: function(data){
..................
}
}
I want to implement AJAX polling mentioned in this answer. Now I want to break out of polling when server return particular data value. How to do that?
Try something like this (where you change the condition to set continuePolling false to whatever you need):
(function poll() {
var continuePolling = true;
setTimeout(function() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
if (data.length == 0)
{
continuePolling = false;
}
},
dataType: "json",
complete: function() { if (continuePolling) { poll(); }),
timeout: 2000
})
}, 5000);
})();
I looked and tried everything in the other questions. Still couldn't solve my memory leak. Here's the code. Essentially it gets a JSON file from a server and updates the table accordingly. It loops the AJAX call every 5 seconds.
Memory leak happens in this AJAX call.
Any help would be great.
LoadDataTable: function(){
$.ajax({
url: "***************************.json",
dataType: 'json',
cache: false,
timeout: 5000,
success: function(data) {
this.setState({temp1:data[2].field3}),
this.setState({temp2:data[2].field5}),
this.setState({temp3:data[2].field25}),
this.setState({temp4:data[2].field26});
if(data[2].field3 > 9 || data[2].field5 >9||data[2].field5>9 ||data[2].field26>9){
document.location.href='#/'
}
else{
//console.log("Stopped playing");
}
setTimeout(this.LoadDataTable, 5000);
}.bind(this),
error: function(request, status, err) {
//request.abort();
console.log(request);
setTimeout(this.LoadDataTable, 5000);
}.bind(this),
})
},
componentDidMount: function() {
this.LoadDataTable();
//this.setInterval(this.LoadDataTable, 100);// Call a method on the mixin
},
Try moving your success and error functions out to a named function like this:
$.ajax({
url: "***************************.json",
dataType: 'json',
cache: false,
timeout: 5000,
success: this.successTimeout,
error: this.errorTimeout,
})
componentDidMount: function() {
this.LoadDataTable();
//this.setInterval(this.LoadDataTable, 100);// Call a method on the mixin
},
successTimeout(data) {
this.setState({temp1:data[2].field3}),
this.setState({temp2:data[2].field5}),
this.setState({temp3:data[2].field25}),
this.setState({temp4:data[2].field26});
if(data[2].field3 > 9 || data[2].field5 >9||data[2].field5>9 ||data[2].field26>9){
document.location.href='#/'
}
else{
//console.log("Stopped playing");
}
setTimeout(this.LoadDataTable, 5000);
}.bind(this),
errorTimeout(request, status, err) {
//request.abort();
console.log(request);
setTimeout(this.LoadDataTable, 5000);
}.bind(this)
Also, you might want to think about using the fetch API. Just be sure to include the polyfill for browser compatibility
I want to start an ajax loop with GET-requests to check statuses from my controller. Once the loop is started i want to start a file download by changing window.location.
However i get no console.logs from this code, why?
function getExcelIKT() {
setInterval(function () {
$.ajax({
type: 'GET',
url: getDownloadCSVForIKTStatusUrl,
dataType: 'json',
async: 'true',
success: function (DownloadCSVForIKTStatus) {
console.log(DownloadCSVForIKTStatus);
}
});
}, 3000);
window.location = downloadExcelUrlIKT;
}
function getExcelIKT() {
setInterval(function () {
$.ajax({
type: 'GET',
url: getDownloadCSVForIKTStatusUrl,
dataType: 'json',
async: 'true',
success: function (DownloadCSVForIKTStatus) {
console.log(DownloadCSVForIKTStatus);
if (false) { //change to some conditions
window.location = downloadExcelUrlIKT;
}
}
});
}, 3000);
}
Just change if (false) { to something if (DownloadCSVForIKTStatus.success) {
Why don't you see console.logs? Because setInterval and $.ajax functions are asynchronous. For example
setTimeout(function () {
console.log(1);
setTimeout(function () {
console.log(2);
},0);
console.log(3);
},0);
console.log(4);
Result will be 4 1 3 2. (I use setTimeout instead of setInterval, which is also asynchronous even with timeout of 0 seconds)
Why the final console log is undefined?Variable time has a global scope and ajax call is async.
This is my code:
var time;
$.ajax({
async:"false",
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function(data) {
console.log(data);
time=data;
},
error: function(data) {
console.log("ko");
}
});
console.log(time);
Change async to the boolean false.
http://api.jquery.com/jQuery.ajax/
var time;
$.ajax({
async: false,
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
console.log(data);
time = data;
},
error: function (data) {
console.log("ko");
}
});
console.log(time);
Also, note that if you need to use dataType: 'jsonp' here for cross-domain, you won't be able to synchronize -- so use a promise.
var time;
$.ajax({
dataType: 'jsonp',
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
time = data;
},
error: function (data) {
console.log("ko");
}
})
.then(function(){ // use a promise to make sure we synchronize off the jsonp
console.log(time);
});
See an example like this here using Q.js:
DEMO
In your code, you initialize the global variable 'time' as 'data'. Where does this data variable come from? If the data variable is not global also, when you try to use console.log(time); , it may be undefined because the data variable is undefined.
Make sure both variables are within scope to be used globally. That might work. Good luck!
OK, a bit contrived, but I hope it shows the point regarding scope of time and timing ...
$.ajax({
async: false,
dataType: 'jsonp',
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
console.log(data.dateString);
time = data.dateString;
},
error: function (data) {
console.log("ko");
}
});
window.setTimeout("console.log('time: '+time)",3000);
JSfiddle