Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout with or without anonymous function? What's the difference?

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

like image 296
Paolo Alfredi Avatar asked Mar 12 '13 08:03

Paolo Alfredi


3 Answers

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.

like image 62
Jonas Høgh Avatar answered Sep 19 '22 11:09

Jonas Høgh


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.

like image 22
Munim Avatar answered Sep 18 '22 11:09

Munim


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.

like image 41
Stuart Grant Avatar answered Sep 22 '22 11:09

Stuart Grant