-4

Running the code, the browser will display RangeError.

enter image description here

function hide() {
    h -= step;
    pp.style.height = h + "px";
    setTimeout(hide(), 1);
}
Addison
  • 7,322
  • 2
  • 39
  • 55
LiJing
  • 155
  • 1
  • 4
  • MitchWheat and @thefourtheye - I'm sure this is a duplicate of *something*, but not the linked question. The question title is misleading - it doesn't reflect the code shown in the screenshot, which is an infinite recursion problem. – nnnnnn Oct 31 '16 at 06:20
  • 1
    Don't post images, post text. See [*How to create a minimal, complete and verifiable example*](http://stackoverflow.com/help/mcve). – RobG Oct 31 '16 at 06:30
  • I don't understand the title and the full code (featuring `h` and `step` vars) is not shown. Consider editing the question. Though my answer might help you. – notgiorgi Oct 31 '16 at 06:38
  • The question title only has additional quotes that shouldn't be there to match the code given. Maybe that's the only inconsistency here? – Mario Oct 31 '16 at 06:55

2 Answers2

1

The problem is this line:

setTimeout(hide(),1);

Rather than telling JavaScript to call hide() again in 1 millisecond you actually call it immediately and only pass it's return value to setTimeout(). This causes an infinite recursion, which in the end causes the stack overflow/error you're getting.

To fix this, you'll have to use either syntax from your question's title:

  • Pass the function name only rather than calling it (better here).
  • Pass a lambda function.
  • Or pass the call inside a string that will be evaluated (IMO should be avoided or replaced with a lambda expression).

However, in your specific scenario I'd suggest using set Timeout(), considering your code is reasonably simple to always finish in time:

// Start the while thing
var handle = setInterval(hide, 1);

// Actual function
function hide()
{
    // Do stuff

    // End condition
    if (done)
        clearInterval(handle);
}
Mario
  • 35,726
  • 5
  • 62
  • 78
0

This code doesn't terminate, so it creates infinite number of stacks which causes stack overflow.

Consider adding some termination logic, like:

if (h < 0) { return }

This terminates the execution of hide() function when h is less then 0.

I'm assuming h and step are some global vars.

Also you're calling hide immediately and passing the value to setTimeout.

Correct way to recursively call function with timeout will be to pass function as value to setTimeout function:

setTimeout(hide, 1)

which is equivalent to:

setTimeout(function() { hide() }, 1)
notgiorgi
  • 1,691
  • 12
  • 27
  • 1
    While this would help in some instances, it wouldn't fix the actual issue: The function is supposed to be called in an interval, but it's actually a recursive call happening immediately. – Mario Oct 31 '16 at 06:53