It is my understanding that setTimeout() can be used to stop code from executing temporarily, however this doesn't seem to be the case in the following code:
...}).done(function recursionLoad(){
var timerLoad = setTimeout(function(){
},3000)
$.ajax({
type:'GET',
url:'modelBN.xml',
beforeSend: function(){$('#query-results').html('<img src="images/ajax-loader.gif"><p>Loading...</p>'); },
timeout: 10000,
error: function(xhr, status, error){...
So what happens is the AJAX call get made immediately instead being delayed for 3 seconds. Am I just using setTimeout incorrectly or is there something about AJAX that prevents it from working? Thanks for any assistance
setTimeout will call the function you pass to it (in the first argument) after the time you specify in the second argument.
It is not a sleep function, and it won't block other code from running.
If you want to run your call to $.ajax after the time has elapsed, then you need to do so from the function you pass to setTimeout (as opposed to calling setTimeout (with a function that will do nothing after 3 seconds) and then immediately calling $.ajax).
Related
I'm trying to make a removeClass function work right after another function ends, so I have this script to call a fittocontainer:
function fittocontainer(){
$('.fittocontainer').fittocontainer()
}
And I want that after the function 'fittocontainer' ends, apply this function:
setTimeout ( function(){
$('#footer').removeClass("active");
})
How can I integrate the setTimeout function with the 'fittocontainer()' to work after it has just ended?
Is fittocontainer a function that you made? If so, and it is asynchronous, you will have to add a callback like:
function fittocontainer (cb) {
//do some stuff
cb();
}
Then you can call it passing a function or even an anonymous function like:
fittocontainer(function () {
// do stuff afterwards
});
If this function is updating the DOM it is most likely asynchronous. Using a timeout to try and execute code after an async method is very dangerous and should never be done.
If it is synchronous, you can simply call a function on the next line and know that it will execute after fittocontainer is complete.
Also remember that you need a timeout on the setTimeout like:
setTimeout(function(){
$('#footer').removeClass("active");
}, 1000);
that is a timeout of 1 second
setTimeout() is about time (minutes, seconds), if you only want to execute that function at the end, you could just call it, or you could use a callback function:
function fittocontainer(callback){
$('.fittocontainer').fittocontainer();
callback();
}
and then call fittocontainer:
fittocontainer(function(){
$('#footer').removeClass("active");
});
I have searched everywhere for a solution to this but have not been able to find anything thus far (I am probably using the wrong keywords! If this is a duplicate, please point out and I will delete).
Could one of you brilliant SO geniuses kindly explain to me why the following does not work as one would hope? What I mean by this is the complete callback is called before the setTimeout has completed within the success callback and I don't quite understand why.
$.ajax({
url: options.url,
data: options.data,
success: function(){
setTimeout(function(){
console.log('firing');
},2000);
},
dataType: options.dataType,
complete: function(){
console.log('ended');
}
});
Is it because a new thread has been started by the setTimeout within the success callback?
Is this possible to achieve without passing in a callback function into the success callback?
It happens because setTimeout() does not block the execution of code.
Therefore the complete callback fires at the same moment as it would without your call to setTimeout().
You will have to put your console.log('ended'); call into a timeout (too) or call your complete handler inside the timeout. :)
I want to call a function within itself like this:
$(document).ready (
function ready() {
var tester = $.ajax({
async: false,
url: "test_parse.php"
}).responseText;
document.getElementById('test').innerHTML = tester;
setTimeout(ready(), 3000);
}
);
But every time I do this my browser just keeps loading and eventually Apache shuts down (obviously not my expected result). Could you help me to figure out a solution?
setTimeout takes a function reference:
setTimeout(ready, 3000);
not
setTimeout(ready(), 3000);
And that being said, I would also do this:
$(document).ready (
function ready() {
var tester = $.ajax({
url: "test_parse.php",
success: function (data) {
document.getElementById('test').innerHTML = data;
setTimeout(ready, 3000);
}
})
}
);
Because async: false will lock up the browser until that data returns from the server
This is wrong:
setTimeout(ready(), 3000);
This is right:
setTimeout(ready, 3000);
ready() is actually invoking the function. ready is simply a reference to the function, which is what you want.
setTimeout expects a function reference as the first parameter, you have a function invocation which is passing the result of calling ready().
This is causing an infinite loop.
You need to pass in "ready", not "ready()"
setTimeout(ready, 3000);
And if you're trying to queue ajax requests that happen in a structured order, you'll want to fire the setTimeout on success after the previous ajax call, not immediately, otherwise you'll have ajax results returning and updating at arbitrary intervals depending on how the server responds to each request.
$.ajax({
// your ajax settings
}).success(function () {
// fire off the next one 3 secs after the last one completes
setTimeout(ready, 3000);
});
This is better than using the async: false setting, which blocks the browser.
Why are you trying to call the function within itself? Surely all you need to do is move setTimeout outside of the function, then call ready() every 3000ms? What'l do you want your output to be?
In the application I'm building I'm polling for a status update and I have noticed that if the call is made as follows the timeout fires continuously:
setTimeout($.get("http://localhost:8080/status", function(data) { UpdateStatus(data);}), 1000);
While if use a function instead the timeout fires every 1000 ms:
setTimeout(function() {$.get("http://localhost:8080/status", function(data) { UpdateStatus(data);})}, 1000);
Why?
In the first example, you're calling $.get and then passing its return value into setTimeout. In the second example, you're not calling the function at all; you're giving setTimeout a function that it will call later, which will then call $.get for you.
This is easier to see with a simpler test case:
function test() {
alert("Hi there!");
}
// WRONG, *calls* `test` immediately, passes its return value to `setTimeout`:
setTimeout(test(), 1000);
// Right, passes a reference to `test` to `setTimeout`
setTimeout(test, 1000);
Note that the first one has parentheses (()), the second one doesn't.
When you want to pass parameters to the function, you have to do it indirectly by defining another function:
function test(msg) {
alert(msg);
}
// WRONG, *calls* `test` immediately, passes its return value to `setTimeout`:
setTimeout(test("Hi there!"), 1000);
// Right, passes a reference to a function (that will call `test` when called) to `setTimeout`
setTimeout(function() { test("Hi there!"); }, 1000);
In the first example the first parameter to setTimeout is getting assigned the result of $.get (wrong), whereas in the second example it is actually receiving a parameter of type function, which will be correctly evaluated as a set of javascript statements every x milliseconds.
You shouldn't be passing the result of a function call to setTimeout - there's no sense in doing that.
First argument should be the function itself, not the call.
Why it fires continuously - a strange side-effect, who knows :)
When the user refreshes the page, defaultView() is called, which loads some UI elements. $.address.change() should execute when defaultView() has finished, but this doesn't happen all the time. $.address.change() cannot be in the success: callback, as it's used by the application to track URL changes.
defaultView();
function defaultView() {
$('#tout').fadeOut('normal', function() {
$.ajax({
url: "functions.php",
type: "GET",
data: "defaultview=true",
async: false,
success: function (response) {
$('#tout').html(response).fadeIn('normal');
}
});
});
}
$.address.change(function(hash) {
hash = hash.value;
getPage(hash);
});
I'm at a loss as to how to make $.address.change() wait for defaultView() to finish. Any help would be appreciated.
Call it in the success or complete callback. Using delay for timing a callback is unreliable at best. You might even need to put the call to it in the callback to the fadeIn function inside of the success callback.
It doesn't have to be defined inside the success callback, just executed. Both contexts will still be able to use it.
I too was told that because of async you can't make javascript "wait" -- but behold an answer :D ...and since you're using jQuery, all the better:
use jQuery's bind and trigger. I posted an answer to a similar problem at How to get a variable returned across multiple functions - Javascript/jQuery
One option is to hide the $.address (I'm guessing this is a drop-down list) via css, and show it inside the success callback from the ajax method.