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?
You should be calling with
and NOT with
In other words, the function you want to call after 1000 ms is test, not the result of calling test!
The reason why
works is that the function you call after 1000ms is a function that calls test, which is basically
testitself. For lambda calculus geeks, that’s called eta-reduction.