Reputation: 346
This is an issue with Javascript executing linearly on a single thread.
using
setTimeout(function(){},time);
is evaluated and executing the function()
immediately.
I am looking for a method to execute function()
in x seconds, for example after the dom has been updated from an ajax call.
How is this done?
In other words just need to 'pause' the script and then let it know when to execute.
for clarity if you did something like this inside the function();
var a= document.getElementbyId("anid").innerHTML;
var a will be gathered at time setInterval is processed and not in x seconds when the function is executed.
Thanks...
Upvotes: 2
Views: 14291
Reputation: 26885
Your example with setTimeout would not execute the function immediately, but after waiting the number of milliseconds specified by 'time'. For example, to show an alert in 3 seconds:
window.setTimeout ( function() { alert ('Test'); }, 3000);
Note that even if you use 0 as time value, the execution of the function is still delayed until the current Javascript execution stack ends, which is useful under certain circumstances but not in your case.
As said by santiagoIT, you should never rely on this kind of strategy to perform any action that depends on a particular AJAX call having completed. Instead, you should use callback functions. This is because when using timers, DOM could still be not ready at the time your function executes (for example if the computer is running slow), this threading problem is known in Computer Science as "Race Condition".
To avoid race conditions, use callback functions. An example using the jQuery library would look like:
$.get("/url/ajax/getSomething", parameterArray, callbackFunction);
function callbackFunction(data) {
// in this example, 'data' contains the response object
// see each function doc to find their callback arguments
alert ('Work with DOM here');
}
Upvotes: 5
Reputation: 9431
It is better that you execute your function after the ajax call finishes. You can register a success/failure function that will get called once the call finishes. That is the right way to do it.
Here is an example with jquery:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// here you do whatever you want after ajax is finished
}
});
** EDIT ** Removed the suggestion to pass the callback function as a string based on Quentin's comments below, as it is indeed not a good practice.
Upvotes: 2