简体   繁体   中英

run another function after preceding function has completed?

if i fire up 2 functions like this:

prepare_data();
read_data();

then i guess they are running at the same time. but as you can see function two is depending on the first one, so how can i make the latter one run after the first one is completed?

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.

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.

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();
} 

@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 ?

http://www.w3.org/TR/2009/WD-workers-20090423/

https://developer.mozilla.org/En/Using_web_workers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM