I used this code (followed by an xmlhttprequest that fills the "tcap" textarea):
st=setTimeout(checkme(),4000)
where checkme()
is:
function checkme() {
if (typeof (st) != 'undefined') clearTimeout(st)
if (document.getElementById("tcap").innerHTML.length > 0) {
document.getElementById('waitmsg').style.display = 'none'
} else {
st = setTimeout(checkme(), 1000)
}
}
If I run it, it freezes Firefox 19 with no error message. But if I replace the first argument (both in code and in the checkme() function) with:
st=setTimeout(function(){checkme()},4000)
it works correctly.
So my question is: what's the difference in calling the checkme()
function with or without the anon function? Why in the first case it freezes Firefox?
Thanks
You need to remove the parens in
st=setTimeout(checkme(),4000)
so instead:
st=setTimeout(checkme,4000)
otherwise, the function is invoked right away.
Since you have the same error inside the checkme function, it probably kills your browser due to unbounded recursion.
setTimeout
accepts a function as an argument, and the correct way to pass a function as an argument is either defining it as an anonymous function, or just providing the function name. If you use parenthesis(brackets), you aren't actually passing a function: You are executing the function and passing the result of the function to setTimeout.
Hence, when specifying a function in setTimeout, and anywhere else you need to pass a function as an argument, you should not use parenthesis.
You shouldn't be using the parenthesis within the setTimeout function. You should only be passing in a reference to the method. What you are doing is invoking the method and passing the return value in to the set timeout method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With