my dog learned polymorphism*
The moose likes HTML, CSS and JavaScript and the fly likes Chaining JavaScript Functions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Chaining JavaScript Functions" Watch "Chaining JavaScript Functions" New topic
Author

Chaining JavaScript Functions

J Miller
Ranch Hand

Joined: Oct 21, 2010
Posts: 67
I was wondering if there is a way in JavaScript to make sure that one function doesn't run until a previous one is finished. Generally, it isn't a problem. But I do run some functions in my work that take a few seconds to complete. And by then the next function in the line has already started. Problem is the second function might be reliant on data from the first. Take this example code for example:





If you open up your console and run this, you'll notice that it prints all of the numbers from the B loop before the A loop, because the A loop has a 2 second delay on it. I need to find a way to be able to line up multiple functions, but make sure that B doesn’t run until A is done, and C doesn't run until B is done, etc. Is this possible?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60802
    
  65

JavaScript is not multi-threaded so functions never run until whatever's currently running stops. If you delay the function using setTimeout, then of course it's not going to run until everything else that started running before it has finished.

If you want fine-grained control over queuing up functions, you could check out the queue() and dequeue() functions of jQuery.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
wood burning stoves
 
subject: Chaining JavaScript Functions
 
Similar Threads
input/output stream
adding and deleting a row in html
Export HTML table data to Excel sheet using ActiveX
window.onload in self invoking function
console.log function not working.