Running the code, the browser will display RangeError.
function hide() {
h -= step;
pp.style.height = h + "px";
setTimeout(hide(), 1);
}
Running the code, the browser will display RangeError.
function hide() {
h -= step;
pp.style.height = h + "px";
setTimeout(hide(), 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:
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);
}
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)