3

I want to know how Javascript handles callbacks inside a recursive call, are the callbacks pushed right into the queue on each of the recursive calls or after the call resolves with a base case?

Test case code

function enums(start,end,callback) {
  callback(start);
  if (end == 1)
    return 1;
  else{
    return enums(start + 1, end - 1, callback);
  }
}

var callback = function (number){
   console.log(number);
}
enums(1,10,callback);
1
  • You can both test and verify this by simply running your code in the console. As long as you're not running async code, the code is executed in order. Commented Aug 10, 2015 at 18:54

1 Answer 1

2

Recursive calls are handled the same way as any other programming language. The code will be as executed as if you were iterating on array and call a function inside the loop. If you would span a timer using setTimeout with a delay of 0 milliseconds after calling your enums function you will notice that the setTimeout callback will be executed after the return of the recursion.

function enums(start,end,callback) {
   callback(start);
   if (end == 1)
      return 1;
   else{
      return enums(start + 1, end - 1, callback);
   }
}

var callback = function (number){
  console.log(number);
}
enums(1,10,callback);
setTimeout(function(){ console.log("Rick"); }, 0);

the output should be: 1..10 and then Rick

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.