0

I have one concern about javascript callback function. What I understood is callback function should allow other statements to proceed if it takes time. So I have created one custom callback function to check but I'm not getting expected result. Am I doing wrong anything here?

function test(param1,param2,cb){
  if(typeof(cb) === 'function') return cb(param1,param2)
  else console.log('im not a func');
}

function calbackFunc(a,b){
    console.log('Hi i am '+a+' '+b);  
}
setTimeout(function timeout(){
        console.log('timeout')
},0);

test('callback','function',calbackFunc);

console.log('console');

Output

"Hi I am callback function"

"console"

"timeout"

As per the callback function, 'console' should come first. but it's not happening. Like setTimeout is working fine. Then why my custom callback function behaving like setTimeout.

lazzy_ms
  • 1,169
  • 2
  • 18
  • 40
Liton
  • 21
  • 6
  • You're logging `console` after running your callback function. – Sebastian Olsen Jul 11 '18 at 11:29
  • 2
    A "callback" is just a regular function passed as a parameter. So it is synchronous like other functions. – TiiJ7 Jul 11 '18 at 11:30
  • The callback you are passing runs before `test()` finishes executing. Calling `setTimeout` with a delay of 0 will not run the passed function immediately, it's still getting scheduled. It will just run very very soon. –  Jul 11 '18 at 11:30
  • Possible duplicate of [Asynchronous behavior and callbacks in javascript](https://stackoverflow.com/questions/36847917/asynchronous-behavior-and-callbacks-in-javascript) – str Jul 11 '18 at 11:31
  • Then how can i make asynchronous callback function without using SetTimeout – Liton Jul 11 '18 at 11:39
  • The functions will execute when their turn arrives in the script, synchronously except for those which are schedule not to return the result immediately e.g. `setTimeout()`, `setInterval()` and function returning a deferred object like XHR (Ajax) call. – Rohit416 Jul 11 '18 at 11:40
  • @user3790136 What is your expected output? "console" > "Hi i am callback function" > "timeout" ?? – Rohit416 Jul 11 '18 at 11:45
  • @Rohit416, Yes but I don't want to move up console physical. It should print asynchronously like this "console" > "Hi i am callback function" > "timeout" – Liton Jul 11 '18 at 11:47
  • [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), it would be a nice read. You may or not use it now but it will be helpful. – Rohit416 Jul 11 '18 at 12:05
  • @Liton "*How can i make asynchronous callback function without using SetTimeout*" - you can't. That's how asynchrony works. https://stackoverflow.com/q/22286887/1048572 – Bergi Jul 11 '18 at 12:45

1 Answers1

1

You're getting confused between the Stack and the Queue.

The Event Loop

In javascript, synchronous calls are going into the stack while asynchronous calls are going into the Heap, and when done are back in the Queue. A function is moving from the Queue to the Stack only when it's empty.

enter image description here

In your example

phase 1: call setTimeout()

this puts the function in the heap, and since the timeout is set to 0, it right away moves to the _queue. does it means that it's executing right away? no, because that your current function (the "main") hasn't finished yet.

phase 2: call test()

this code is synchronous! when calling test we add a function to the stack. then we add the cb() call to the stack. that means that we need to finish all both before we can proceed to phase 3.

phase 3: console.log

nothing to explain here

post phase 3

the current "main stack is finished, so the function from the queue is now added ti the stack, logging 'timeout'.

ronapelbaum
  • 1,617
  • 14
  • 19