ferdinandfly
ferdinandfly

Reputation: 371

Can't get setTimeout in javascript to work properly

I have a function in javascript:

function test(){
...
    if (){
        setTimeout(test(), 1000);
    }
}

according to the manual, i can call this with:

setTimeout(test(), 1000);

in fact, it calls, but do not wait the 1s. so I try to use it like the following and it works.

setTimeout(function(){test();}, 1000);  

Anyone can explain this to me?

Upvotes: 2

Views: 225

Answers (3)

Andreas Wong
Andreas Wong

Reputation: 60506

Which manual? Calling test() would call things returned by test() and pass it to setTimeout, so unless your test() is returning a function, this won't work.

You could use the anon function alternative, or you can pass it like setTimeout(test, 1000) without the ().

Another bad usage you might find along the way is to pass it as string like:

setTimeout("test()", 1000)

avoid this at all cost, as this is equivalent to calling eval and you'll run into scoping issue sooner or later.

Upvotes: 3

Chris Baker
Chris Baker

Reputation: 50592

setTimeout expects a function reference. When you pass it this:

setTimeout(test(), 1000);

That is passing the result of calling the test function to setTimeout. Instead, pass it the reference to test itself:

setTimeout(test, 1000);

Want to see something fancy?

function test () {
    var what_are_you = 'a closure';
    return function () {
       alert('I am '+what_are_you+'!')
    }
}
setTimeout(test(), 1000);

Here, I am returning a function reference from a function call. See the article below for more info on that!

Documentation

Upvotes: 1

Ray Toal
Ray Toal

Reputation: 88378

You should be calling with

setTimeout(test, 1000);

and NOT with

setTimeout(test(), 1000);

In other words, the function you want to call after 1000 ms is test, not the result of calling test!

The reason why

setTimeout(function(){test();}, 1000);  

works is that the function you call after 1000ms is a function that calls test, which is basically test itself. For lambda calculus geeks, that's called eta-reduction.

Upvotes: 2

Related Questions