Function is not defined, when using setInterval or setTimeout

Javascript can be challenging and is full of traps for the beginners. Today I was caught into one of such traps and I was struggling with Uncaught ReferenceError, functionName() is not defined error, for way to long. Solution seems easier than I was thinking, so I wrote this short memo to future myself to avoid falling into the same trap again.

The solution is as simple as changing call to anonymous function. Instead of:

setInterval('functionName()', 1000);

use:

setInterval(function(){functionName()}, 1000);

Why is this happening? Is this a bug in Javascript? Yes and no. It is a bug, but in your code, not in Javascript! :]

Refer to this great explanation. To cite:

(…) when you attempt setInterval(funcName(), 100), you are actually calling the function and passing its return value to setInterval, which is incorrect.

The same goes for setTimeout(). And you have to use this approach (anonymous function), if you need to call any function repeatedly with some parameters.

2 comments on “Function is not defined, when using setInterval or setTimeout

Leave a Reply to John DoeCancel reply