Reputation: 9044
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 setTimeout()
. Yes, I could use setInterval()
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(){
console.log("polled")
setTimeout(messagePolling(),1000) // <--- removing `()` from the function works as intended
}
messagePolling();
What is the logic behind this? messagePolling
is a function after all isn't it.
Upvotes: 0
Views: 89
Reputation: 377
Anywhere a function name contains "()" it is executed immediately except when it is wrapped in quotes i.e is a string.
Upvotes: 0
Reputation: 28177
Written as
setTimeout(messagePolling(),1000)
the function is executed immediately and a setTimeout
is set to call undefined
(the value returned by your function) after one second. (this should actually throw an error if ran inside Node.js, as undefined
is not a valid function)
Written as setTimeout(messagePolling,1000)
the setTimeout
is set to call your function after one second.
Upvotes: 1
Reputation: 947
When you type messagePolling
you are passing the function to setTimeout
as a parameter. This is the standard way to use setTimeout.
When you type messagePolling()
you are executing the function and passing the return value to setTimeout
That being said, this code looks odd to me. This function just runs itself. It's going to keep running itself indefinitely if you do this.
Upvotes: 0
Reputation: 7151
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?
Upvotes: 5