Skip to content Skip to sidebar Skip to footer

(infinite?) Loop In Javascript Code

I have the following JavaScript code to 'display' XML on a website: function createChild(node,tabindex){ var child = node.childNodes; var r = ''; var tabs = '';

Solution 1:

This is why you should always declare your variables:

// declare 'i'for(var i =0; i < tabindex ; i++){
  tabs +="\t";
};

If you don't declare i in the function scope, it will be global, thus interfering with the for loop in a recursive function call:

  1. The i variable is set to 0 in the first function call.

  2. The function is calls itself.

  3. The i variable is set to 0.

  4. The function returns.

  5. i is now 0 again, so the loop in the first frame will run forever.

So somewhere in the createChild function, you have to declare i, either before the first loop or in the first loop. You can also use let.

Post a Comment for "(infinite?) Loop In Javascript Code"