I am pretty new in JavaScript and I have to perform an operation after some time that another previous operation is performed.
So I have this function:
function validaProgetti() {
$.ajax({
type: "POST",
//data: {'checkedRowList' : checkedRowList},
data: JSON.stringify(checkedRowList),
url: "validaProgetti",
contentType:"application/json"
}).done(function(response) {
$('.modal').modal('hide');
sostituisciFrammentoJsp('outputRicerca', response);
//alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
}
As you can see into the done() body I have these 2 call:
$('.modal').modal('hide');
sostituisciFrammentoJsp('outputRicerca', response);
I need that the sostituisciFrammentoJsp() execution is performed after 3 seconds of delay to ensure that the previoius function is complete.
How can I correctly set a delay for this function?
...after 3 seconds of delay to ensure that the previoius function is complete.
Let's do better than that, and actually wait for the previous function to complete:
$('.modal').modal('hide').one("hidden.bs.modal", function() {
sostituisciFrammentoJsp('outputRicerca', response);
});
(Note I used one, not on, so the handler gets autoremoved after the event occurs.)
Note that I've assumed there you're using a Bootstrap modal, but other "modal" libraries will offer a similar event or callback.
But answering the question you actually asked, you can set up a callback after three seconds with setTimeout:
$('.modal').modal('hide');
setTimeout(function() {
sostituisciFrammentoJsp('outputRicerca', response);
}, 3000);
The number at the end is in milliseconds (thousanths of a second).
Just use javascript setTimeout
setTimeout(function(){
// your code here
}, timeInMillis);
Using this command will schedule an operation for the time you pass.
Option : 1
clearTimeout(window.timer);
window.timer=setTimeout(function(){ // setting the delay for each keypress
ajaxSearchRequest($type); //runs the ajax request
}, 3000);
Option : 2
// set your delay here, 2 seconds as an example...
var my_delay = 2000;
// call your ajax function when the document is ready...
$(function() {
callAjax();
});
// function that processes your ajax calls...
function callAjax() {
$.ajax({
// ajax parameters here...
// ...
success: function() {
setTimeout(callAjax, my_delay);
}
});
}
Related
I have a function that needs to be called after 5 seconds time interval. This function processes AJAX request in the background (the request goes to other website, so it may take a few seconds). The function is as follows:
function myFunction() {
var sendData = {
cid: cid
};
$.post('xyz.com/somepage.php', sendData, function(response) {
//processes the response
});
setTimeout(myFunction, 5000); //call again after 5 seconds
}
I need to consider a fact that some users may have slow internet connection and the request can take time more than 5 seconds. So, I need to avoid calling that function (or we say avoid sending request) again until its job is finished. I tried the method given in the last paragraph on this link, but it didn't work. Any suggestion? Thanks.
You can call the function on completion of ajax call
function myFunction() {
var sendData = {
cid: cid
};
$.post('xyz.com/somepage.php', sendData, function(response) {
//processes the response
}).done(function() {
setTimeout(myFunction, 5000); //call again after 5 seconds
});
}
Place the setTimeout call within the callback handler:
function myFunction() {
$.post('xyz.com/somepage.php', { cid: cid }, function(response){
//processes the response
setTimeout(myFunction, 5000);//call again after 5 seconds
});
}
I've been struggling creating a reload functionality when a getJSON call fails. This is my current code:
function get_stuff(page) {
fPage = 'http://mywebsite.com/' + page + '.json';
$.getJSON(fPage, function (data) {
// Stuff
})
.fail(function () { // Call failed
get_stuff(page);
});
This code does reload the function, but a couple of times every millisecond. I thought of adding a delay, however I didn't manage to find a function (I tried delay(ms) and sleep(ms))
I hope anyone is able to help me out
setTimeout(function, ms)
Example
setTimeout(function(){
get_stuff(page)
}, 1000)
// the function will be executed after 1 second
I previously asked about a question using Ajax polling from a server every 3 seconds using the following jQuery Ajax request:
function getData() {
$.ajax({
url : 'http://example.com',
type: 'GET',
success : function(data) {
// process data here
setTimeout(getData, 3000);
},
dataType : 'json'
});
}
It seems that another way of doing this is putting setTimeout outside $.ajax() block:
function getData() {
setTimeout( function() {
$.ajax({
url : 'http://example.com',
type: 'GET',
success : function(data) {
//process data here
},
dataType : 'json'
}) }, 3000);
}
So is there any difference between these two methods? Do they have the same effect of continuous polling the server every 3 seconds?
Also, inside the success callback function, how do I terminate this infinite polling if certain condition is met, say, data.length>1000 then I want to terminate this loop and call another function? Should I do something like this:
function getData() {
var tID = setTimeout( function() {
$.ajax({
url : 'http://example.com',
type: 'GET',
success : function(data) {
//process data here
if(data.length > 1000) {
funcOutside();
clearTimeout(tID);
}
},
dataType : 'json'
}) }, 3000);
}
The second option won't poll every 3 seconds; it will only poll just once.
To conditionally continue or stop polling you should use a variation of the first option: add a conditional around the setTimeout call.
function getData() {
$.ajax({
url : 'http://example.com',
type: 'GET',
success : function(data) {
// depending on the data, either call setTimeout or simply don't
if( /* data says continue polling */) {
setTimeout(getData, 3000);
}
},
dataType : 'json'
});
}
So is there any difference between these two methods? Do they have the same effect of continuous polling the server every 3 seconds?
Yes, there is an important difference! The first version will queue a call to the function after the response arrives. So the interval between calls will be (roughly) 3000ms plus the time the request/response took.
The second version will make a request after 3 seconds, then stop. If you change setTimeout to setInterval, it would make a new request every 3 seconds, but there would be no guarantee the previous request will already have completed when a new one is made (if one request takes ~3000ms). So the first version is probably what you're looking for.
About terminating the loop: yes, just add a condition like the one you have in your code. But instead of clearing the timeout, just don't add a new one:
//process data here
if(data.length > 1000) {
funcOutside();
} else {
setTimeout(getData, 3000);
}
Final note: technically, that's not recursion, because it's not getData calling itself, but the callback from setTimeout calling getData all the time.
(function loopsiloop(){
setTimeout(function(){
$.ajax({
url: 'foo.htm',
success: function( response ){
// do something with the response
loopsiloop(); // recurse
},
error: function(){
// do some error handling. you
// should probably adjust the timeout
// here.
loopsiloop(); // recurse, if you'd like.
}
});
}, 5000);
})();
This will do the work for you.
I'm doing three things here:
Declaring a function loopsiloop that is immediately invoked (notice the parens at the end).
Declaring a timeout handler to fire after 5 seconds.
Polling the server inside the timeout, which upon either success/failure will call loopsiloop and continue the poll.
I want to make an ajax call after every 1 min but the succeeding call should be made only after the preceding ajax call was completed. For example ajax call 2 should be made only after ajax call 1 is completed.
I know how to make a function execute every 1 min with setInterval.
thanks in advance
Try something like this:
(function repeatAjaxCall() {
$.ajax({
url: "example-url.com",
complete: function() {
setTimeout(repeatAjaxCall, 60000)
}
});
})();
Have you taken a look at the Underscore js debounce function?
http://underscorejs.org/#debounce
Basically, these allow you to call a "debounced" version of the function that will not be called until x number of milliseconds since the last call.
This will allow you to do something like this:
var update = _.debounce(function() {
// do some ajax stuff here
}, 300);
setTimeout(update, 1000);
function ajaxCall(){
setTimeout(function(){
$.get( url, function(data){
// do stuff
ajaxCall();
})
}, 60000)
}
As you are saying. If the next call will be fired just when the previous one has finished. And the previous one can delay more than 1 minutes. Let's supose, 2 minutes. So the next one will be called at least within 2 minutes delay. So knowing that. It's ok that will never work minute by minute, right?
So why not call the next ajax when the last one is completed, instead of fire it minute after minute? Using the complete method:
$.ajax({
url: 'file',
type: 'POST',
data: {},
complete: function(xhr, textStatus) {
//CALL HERE THE NEXT AJAX
},
Or if want to give a time of 1 minute after the the previous one is completed:
$.ajax({
url: 'file',
type: 'POST',
data: {},
complete: function(xhr, textStatus) {
setTimeout(function(){
//CALL HERE THE NEXT AJAX
}, 1000)
},
I have a javascript function which supposed to check whether a task is completed.
When the task is completed there is a completion record in a file on the server.
The function supposed to make recursive calls to the server with some delay (potentially increasing) till it gets the completion record in the file.
The code given below makes excessive calls to the server with interval less than a second
example from Web Console:
[20:06:21.202] [20:06:21.563] [20:06:21.990]
But the task becomes competed on variable waittime value getting equal to max_waittime .
Though for a test case overall output is as expected, something is wrong with the function.
Where I'm wrong?
function check_status(time,div_id,filename) {
var status =0;
var waittime=time;
var max_waittime=11000000;
if (waittime < max_waittime){waittime=waittime+1000000; }
$.ajax({
type: "GET",
async: false,
url: "code_on_server_checking_file.php",
data: "f="+filename,
dataType: "text",
success: function(content) {
if (content ) {
// stuff related to output of the result
....
return status=1;
}
else {return status=0;}
}
});
if (status == 0 && waittime < 20000000){
setTimeout(check_status(waittime,div_id,filename),waittime);
}
else {alert('check_status passed!'+status+'|'+waittime);}
}
You need to pass check_status to setTimeout, not the value returned by invoking check_status(...). Since you need to pass parameters to check_status, use an anonymous function:
setTimeout(function () {
check_status(waittime, div_id, filename);
}, waittime);
You are calling the function instead of giving it as a reference to setTimeout. Wrap your function call in an anonymous function. Also, it would be better to simply set up the call in the ajax callback if needed rather than using a synchronous call. A synchronous call will tie up your browser.
function check_status(time,div_id,filename) {
$.ajax({
type: "GET",
url: "code_on_server_checking_file.php",
data: "f="+filename,
dataType: "text",
success: function(content) {
if (content ) {
// stuff related to output of the result
}
else {
time += 1000000;
if (time < 20000000) {
setTimeout( function() { check_status( time, div_id, filename); }, time );
}
}
}
});
}
"recursive calls to the server"? No, I don't think you want that.
If you go three deep, var max_waittime=11000000; will be created and initialized three times.
Maybe you can set the timeout value for the ajax call (ajax settings)
http://api.jquery.com/jQuery.ajax/
First of all, it looks like you don't understand that the ajax call is an asychronous call. Calling it just starts the networking operation and then the rest of your code continues executing. Some time later when the networking operation completes, your success function is called.
The ONLY place you can operate on the results of the ajax call is in the success function. You can't return a value from the success function and expect that to go anywhere. The only place that goes is somewhere inside the ajax code where it's dropped. If you need to do something with the results of the ajax call, then you need to either do that operation right in the success function or call some other function from the success function and pass it the returned data.
These are the parts of your code that do not work:
There's no point in returning the status value from the success function. It doesn't go anywhere except into the ajax function where the return value is just dropped.
This line of code if (status == 0 && waittime < 20000000){ is not doing what you want. Because the ajax call is asynchronous, the value of status has not yet been set by the ajax call when this line of code runs. Thus, it's ALWAYS 0 so your logic never works. You need to move this logic inside the success handler.
As others have said, your parameters to setTimeout are not right. You have to pass a function to setTimeout, not the results of executing a function.
This is the code I would suggest:
function check_status(time, div_id, filename) {
var max_waittime=11000000;
if (time < max_waittime){
time=time+1000000;
}
$.ajax({
type: "GET",
async: false,
url: "code_on_server_checking_file.php",
data: "f="+filename,
dataType: "text",
success: function(content) {
if (content ) {
// stuff related to output of the result
if (time < 20000000){
setTimeout(function() {check_status(time, div_id, filename)}, time);
}
}
}
});
}
Note that all handling of the ajax result is done in the success function and we pass an anonymous function to setTimeout that re-calls check_status after a time delay. This is not actually recursion (as others mentioned) because setTimeout allows check_status to return before it's called again some time later.