roundcrisis
roundcrisis

Reputation: 17806

setTimeout(fn(), delay) doesnt delay as expected

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?

Upvotes: 2

Views: 919

Answers (4)

Alex Gyoshev
Alex Gyoshev

Reputation: 11977

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.

Upvotes: 2

Wookai
Wookai

Reputation: 21773

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

Upvotes: 1

EFraim
EFraim

Reputation: 13038

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.

Upvotes: 4

JoshBerke
JoshBerke

Reputation: 67108

Try

setTimeout(myFn,20000);

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

Upvotes: 12

Related Questions