Reputation: 21
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');
"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.
Upvotes: 0
Views: 1272
Reputation: 1807
You're getting confused between the Stack and the Queue.
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.
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.
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.
console.log
nothing to explain here
the current "main stack is finished, so the function from the queue is now added ti the stack, logging 'timeout'
.
Upvotes: 1