views:

124

answers:

4

hi all

I must be missing something quite obvious here because something rather strange is happening

I have a bit of js code that goes pretty much like this

setTimeout(myFn(), 20000);

If I m correct when I hit that line, after 20 seconds myFn should run right?

in my case myFn is an ajax call and it happens quite fast ( not at 20seconds and I just dont understand why. Any ideas or pointers?

+10  A: 

Try

setTimeout(myFn,20000);

When you say setTimeout(myFn(),20000) your telling it to evaluate myFn() and call the return value after 20 seconds.

JoshBerke
+3  A: 

The problem is that myFn() is a function call not function pointer. You need to do:

 setTimeout(myFn, 20000);

Otherwise the myFn will be run before the timer is set.

EFraim
A: 

Remove the (). If you put them, the function is called directly. Without them, it passed the function as argument.

Wookai
+1  A: 

No, the correct line would be setTimeout(myFn, 20000);

In yours, you're actually calling the myFn without delay, on the same line, and its result is scheduled to run after 20 seconds.

Alexander Gyoshev