Click here to Skip to main content
15,844,673 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
callback is function is asynchronous right? when we send function as a argument and we call callback, is it making callback function synchronous always? If i get answer "yes" then i don't have doubts in callback. so help me Am i right or wrong?

What I have tried:

function a() {
  setTimeout(function() {
    console.log("hi")
  }, 5000)
}

function b() {
  console.log("hello");
}

a();
b();


// hello
// after 5 seconds hi


which is in asynchronous

BUT

function a(callback) {
  setTimeout(function() {
    console.log("hi");
    callback();
  }, 5000)
}

function b() {
  console.log("hello");
}

a(b);


// after 5 seconds hi
// hello

This is how it works all the time?
Is callback function making synchronous all the time?
Posted
Updated 3-Jan-19 8:00am

1 solution

The first code snippet you call "a" which sets up a timer so that "hi" is written after 5 seconds. You then call "b" so "hello" is written immediately. What you'll see in the console is the immediate "hello" then after 5 seconds "hi".

In the second code snippet you call "a" and pass "b" as a parameter. "a" starts a timer so that after 5 seconds it writes "hi" and then calls whatever method you passed in as a param (b). So in the console you'll get nothing right away, and after 5 seconds get "hi" then "hello".

So your code is doing what you're telling it to do, it's nothing to do with synchronous and asynchronous.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900