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.
messagePollingis a reference to a function.messagePolling()invokes the function. You should know that since you havemessagePolling();in the last line of your code snippet ;) And I'm sure you have passed the return value of a function to other functions before, i.e.foo(bar()). This is will callbarand pass the return value tofoo. That's how function invocation works in JavaScript.