Michael Samuel
Michael Samuel

Reputation: 3920

Are javascript functions synchronous or async?

I have the following JS code:

<script>
first();
second();
</script>

I want to make sure that second() will run after complete execution of first(). Is that the expected default behavior?

Upvotes: 4

Views: 2778

Answers (4)

BeNdErR
BeNdErR

Reputation: 17927

It depends on what you have inside your first() and second() functions.. if you have some async calls, first() may end after second().

For example

function first(){
    console.log("I'm first");   
}
function second(){
    console.log("I'm second");   
}

first();
second();

will print

I'm first

I'm second

Now suppose you have an ajax call in your first() function that takes 10 seconds to end:

function first(){
    $.ajax({
        //--- blah blah
        success: function(){
            //--- success runs after 10 seconds
            console.log("I'm first");   
        }
    })
}

if you run

first();
second();

you will have printed

I'm second

I'm first

Here you can find another example

Upvotes: 5

Lakmal Caldera
Lakmal Caldera

Reputation: 1031

Javascript is an Asynchronous language. The reason why they call it an asynchronous language is cause all the functions execute on an event basis, with the help of event handlers and we really can't be sure when the events will fire. It can be a mouse click event, load event, etc. However the execution of functions happen sequentially. Only after the first function execute will the second start. But keep in mind that Javascript is an Asynchronous language and why it is called so. So to answer your question, yes! :)

Upvotes: -2

Max Brodin
Max Brodin

Reputation: 3938

Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row

 first();
 second();     

they will execute in order. second will not start until first has completed.

Upvotes: 0

Robert
Robert

Reputation: 20286

Yes it is expected behavior. You can define also some asynchronous functions like AJAX calls. You can also define behavior that is similar to asynchronous calls check this links

http://krasimirtsonev.com/blog/article/7-lines-JavaScript-library-for-calling-asynchronous-functions

http://jsbin.com/AhirAlOV/5/edit?html,js,output

Important:

Also remember that JavaScript is not multithreaded language. JavaScript will run in a single thread, but will be executed in blocks. So it will have to finish each block of code it has queued up before continuing to the next block. You can get illusion of asynchronous calls with events and callbacks

Upvotes: 2

Related Questions