user3284463 user3284463 - 8 months ago 38
Javascript Question

Calling `Function` vs `Function()` within the same function

I was writing a long polling script and ran into a

too much recursion
error which hung the browser. My goal is to call the same function every 1000ms using
. Yes, I could use
but it is going to be a long polling script and will be waiting for a server response.

I fixed this by removing the
from the function I was calling within the same function.

My script looks like:

function messagePolling(){
setTimeout(messagePolling(),1000) // <--- removing `()` from the function works as intended


What is the logic behind this?
is a function after all isn't it.


You're absolutely right - messagePolling is a function. However, messagePolling() is not a function. You can see that right in your console:

// assume messagePolling is a function that doesn't return anything
messagePolling() // -> undefined

So, when you do this:

setTimeout(messagePolling(), 1000)

You're really doing this:

setTimeout(undefined, 1000)

But when you do this:

setTimeout(messagePolling, 1000)

You're actually passing the function to setTimeout. Then setTimeout will know to run the function you passed - messagePolling - later on. It won't work if it decides to call undefined (the result of messagePolling()) later, right?