Re cursive Jquery function exceeding maximum callstack

I have 2 jquery functions which show and hide li one by one, they are slightly different and I am not sure which one is causing the issue. They probably need a for loop to prevent overloading the callstack, which I have tried, to no avail, so here is the code that makes it work for one time.

$( "#showr" ).click(function() {
  $( "li" ).first().show( "fast", function showNext() {
    $( this ).next( "li" ).show( "fast", showNext );
  });
});

Here is the codepen:

http://codepen.io/damianocel/pen/YWaWJE

Just hover over the sandbox, then the 2 buttons to click will appear.Thank you very much, I would like to understand why and what is happening there.

[quote=“damiano, post:1, topic:231682, full:true”]
I have 2 jquery functions which show and hide li one by one, they are slightly different and I am not sure which one is causing the issue.[/quote]

Interesting - it works the first time you press the open button, but after the close button and trying to open again it has the callstack failure.

No, that’s wrong. Waiting long enough after closing results in the callstack failure. It’s the closing that’s causing the problem.

I think that the following hideNext line is the cause of the problem:

$("li").prev().hide('fast', hideNext)

In the showNext code you have used:

$( this ).next( "li" ).show( "fast", showNext );

Which should be enough information to help direct you towards a solution.

Thank you so much, wrapping the li as this object fixed this.

Just to understand this properly, the programm knows what this is when declared, but when you just say “li” instead it gets confused because there is no proper reference?
One would think it’d just carry on and get the next li etc
Not sure how jQuery works and what it returns from getElementByTagName or how the overall process works.
Another thing, obviously, initially, “this” is the button, until the hodenext/shownext functions are invoked, then the “this” is shifted to be the current event target,is that right?

Thank you for helping and clearing this up

[quote=“damiano, post:3, topic:231682, full:true”]
Just to understand this properly, the programm knows what this is when declared, but when you just say “li” instead it gets confused because there is no proper reference?[/quote]

That’s right. Using “li” means that it gets all LI elements on the page.

Sorry, it doesn’t work that way.

It gives you an array-like structure of all the matching HTML elements on the page.

The this keyword can easily become very confusing, so it can really help to assign it to a variable so that you know what is happening there.

For example:

function hideNext(){
  var li = this;
  $(li).prev().hide('fast', hideNext)
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.