Run Another Function After Preceding Function Has Completed?
Solution 1:
Javascript, and most other languages, run code sequentially.
Therefore, they will not both run at the same time.
In fact, it is not possible to run two different pieces of Javascript code at the same time. However, in many other languages, it is possible using threads.
However, if they make AJAX calls, the corresponding server-side code called by both functions will run simultaneously.
To prevent that, you'll need to make the first function accept a callback parameter and pass it the second function.
Solution 2:
I'm assuming the first call makes some kind of asynchronous call that the second relies upon because otherwise the two functions will execute sequentially.
If so you need to do the second in the callback from the first. For example, in jQuery:
function prepare_data() {
$("#data").load("/load_data.php", function() {
read_data();
});
}
It's impossible to say how you should solve this without more information on whether you're using vanilla Javascript or a particular library. I'd strongly suggest using a library of some sort for AJAX however.
Solution 3:
May be you want to call Second function after first function function to be successfully executed, if so, then you can do this by this
$('button').click(function()
{
function1(someVariable, function() {
function2(someOtherVariable);
});
});
function function1(param, callback) {
alert('Now first function will be called.');
callback();
}
Solution 4:
@SLaks
In fact, it is not possible to run two different pieces of Javascript code at the same time. However, in many other languages, it is possible using threads.
Is this completely correct? cant you run javascript parallely using web workers ?
Post a Comment for "Run Another Function After Preceding Function Has Completed?"