Why is the method executed immediately when I use setTimeout?

Adler picture Adler · Aug 21, 2011 · Viewed 36.3k times · Source

I'm trying to write a simple code with a setTimeout, but the setTimeout just won't wait the time it's supposes to and the code execute immediately. What am I doing wrong?

setTimeout(testfunction(), 2000);

Answer

Mat picture Mat · Aug 21, 2011

You're calling the function immediately and scheduling its return value.

Use:

setTimeout(testFunction, 2000);
                       ^

Notice: no parens.