سؤال

I have a function written in javascript calling itself in a recursive way :

function f(attempt){
    if (attempt + 1 <= 10) {
        setTimeout(f(attempt + 1),2000);
    }
}
f(0);

For an unknown reason the function is effectively called 10 times but without any delay. The setTimeout seems to execute immediately the function f.

However when I do this then everything works fine :

function f(attempt){
if (attempt + 1 < 10) {
    setTimeout(function(){f(attempt + 1);},2000);
}}
f(0);

Do you have an explanation ? Is is because this code is written for Cucumber testing ?

هل كانت مفيدة؟

المحلول

You have to pass the function as a parameter to setTimeout, that means no parenthesis at the end of f. What you are doing right now is calling f and passing it's return value to setTimeout. You can pass arguments to f as the third argument of setTimeout. Your call should look like this:

setTimeout(f, 2000, attempt + 1);

نصائح أخرى

setTimeout(f(attempt + 1),2000);

This code above calls setTimeout function and instead of passing a function to call it passes the result of your f() function, it is invoked right on the spot.

  setTimeout(function() { f(attempt + 1) },2000);

But in this case you are passing a reference to your function to be invoked in a 2000 seconds, so it does not evaluate the function itself on the spot.

You should write it like this. This is an alternative way to do the check and have no private vars.

function f(){
 if(++attempt<10){// not shure 
  setTimeout(f,2000);
 }
}
var attempt=0;
f();

Demo

http://jsfiddle.net/3nm2Q/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top