• Register
100 points
5 1

Synchronous function

As the name suggests ‘synchronous’ means things will go in a systematic manner like:one statement will execute only when previous statement executed.In other words,you can say that one statement will wait till previous statement executes.All things will go one by one.In javascript we can make both synchronous functions and asynchroous funcions.These functions are known as blocking functions or statements.
 

Code

console.log('Welcome');
console.log('to');
console.log('KodLogs');

Output

Welcome
to
KodLogs

Here,first statement is executed first after that only second statement prints.

Asynchronous function

When you are calling the function asynchronously then you do not have to wait for the previous function or statements to be executed.This type of functions are used when we do not want to the user wait for execution.There are some functions which we can use for asynchronous behaviour like setTimeout().
We can also call the function asynchronously through JQuery,AJax or with some web server’s API XMLHttpRequest() etc.They are non-blocking functions.
 

Code1

console.log('Welcome');
jQuery.get('index.html', function (data) {
    console.log("to");
});
console.log('KodLogs');

Output1

Welcome
KodLogs
to           //statement 2 printed last because jquery waits for index.html so that it can pass as argument

Code2

console.log("Welcome");
    setTimeout(() => {
        console.log("to");// it executes after 4secs so it will execute after the "Welcome" and "KodLogs"
    }, 4000);
console.log("KodLogs");
   

Output2

Welcome
KodLogs
to