1. Computing
Send to a Friend via Email

Recursive Calls in JavaScript

Join the Discussion

Questions? Comments?

A recursive call happens when a script calls itself.

There are a couple of things to watch for when using recursive calls. The first thing when calling a function recursively is that you need to make sure that there is some form of exit condition where the function will not call itself recursively. Without such an exit condition the script will just continue to call itself recursively until it uses all the available memory and brings the browser to a halt. The other thing is to make sure that the parameters passed in the recursive call are not the same values as were passed into the function in the first place since if they are then this too will set up an infinite recursion where the exit condition can never be satisfied.

There are in fact two ways that we can do recursive calls within JavaScript. One is to directly code the call within the function like this:

function recurs(p1) {
  p1--;
  if (p1 < 0) return // exit condition
  recurs(p1);
}

The other way to call a function recursively and the way that is actually more commonly used in JavaScript is to do the recursive call indirectly via a getTimeout call. Here is the same code using that call.

function recurs(p1) {
  p1--;
  if (p1 < 0) return // exit condition
  setTimeout("recurs("+p1+")",1);
}

This way of recursively calling the function avoids having the function call itself directly and avoids having the web page locked up completely until the recursive processing completes. By increasing the value in the second parameter to the setTimeout call you can also delay te recursive call making it suitable to use for producing animated effects where the delay controls the speed of the animation.

©2014 About.com. All rights reserved.