Are javascript functions synchronous or asynchronous?
I have the following JS code:
<script>
first();
second();
</script>
I want to make sure that it second()
will be launched after complete execution first()
. Is this the expected default behavior?
It depends on what you have in functions first()
and second()
. If you have asynchronous calls first()
may end up after second()
.
for example
function first(){
console.log("I'm first");
}
function second(){
console.log("I'm second");
}
first();
second();
will print
I am the first
I'm second
Now, suppose you have an ajax call in your function first()
that ends at 10 seconds:
function first(){
$.ajax({
//--- blah blah
success: function(){
//--- success runs after 10 seconds
console.log("I'm first");
}
})
}
if you run
first(); second();
you print
I'm second
I am the first
Here you can find another example
Yes, this is expected behavior. You can also define some asynchronous functions like AJAX calls. You can also define behavior similar to asynchronous calls by checking these 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 a multithreaded language. JavaScript will run on a single thread, but will run in blocks. Thus, he will have to finish every block of code he has queued up before moving on to the next block. You can get the illusion of asynchronous calls with events and callbacks
Most functions in Javascript are synchronous. If you were to call multiple synchronous functions on a line
first(); second();
they will be executed in order. second
does not start before completion first
.
Javascript is an asynchronous language. The reason they call it asynchronous is the reason that all functions are done on an event basis, with event handlers, and we really can't be sure when the events will fire. This could be a mouse click event, a load event, etc. However, the execution of functions occurs sequentially. Only after the first function has been completed will the second start occur. But keep in mind that Javascript is an asynchronous language and why it is called that way. So to answer your question, yes! :)