Reputation: 1309
How can I call an asynchronous function and then create a pause in the code that follows the call to the function so that I may be (almost) sure that the asynchronos function has finished?
I don't want to put the code that follows the call inside a function and then delay it to achieve this, just pause the code as it is for a few seconds.
Here is what I mean:
<script>
asynchronousFunction(); // start running immediatly
waitFor10Seconds(); // only the following code should wait while the async
// function is running in the background
rest of the code; // this code will start running after 10 seconds have passed
// since the async function has been called
</script>
Upvotes: 2
Views: 4693
Reputation: 8200
As mentioned, you should really use a callback. It's easy with jQuery:
$.get("page.php", "key1=value1", function(data) {
// Code in here will be executed when response has been received
});
http://api.jquery.com/jQuery.get/
You can of course use $.post() if you'd rather POST the data.
Upvotes: 2
Reputation: 169373
It's called setTimeout
asyncThing();
setTimeout(function() {
// do stuff
}, 10000);
Ideally though the async operation should allow you to pass a callback so you turn it into
asyncThing(function() {
// do stuff
});
Upvotes: 4
Reputation: 16861
Aldo a callback is better practice, this what you asked for
window.setTimeout(function(){ ... }, 10000);
Upvotes: 1