1

I'm trying this recursion thing in Javascript, and found the numbers are printed out in the wrong order (Desc, whereas I was expecting Asc). Why is this, and how can I visualise the process?

(function hi(x) {
    if (x > 1000) {
        return;
    } else {
        x+=1;
        setTimeout(hi(x), 100000);
        console.log(x);
    }
})(4)
1
  • Try adding another console.log(x) statement before the setTimeout call to help you visualise what happens. Commented May 31, 2015 at 12:58

2 Answers 2

5

Change your code to :

(function hi(x) {
    if (x > 1000) {
        return;
    } else {
        x+=1;
        setTimeout(function (){hi(x);}, 100);
        console.log(x);
    }
})(4)

change is in here:

function (){hi(x);}

This :

 setTimeout(hi(x),

Invokes the function immediately. you don't want that.

You want a function that will run hi(x) after 100000 ms.

Sign up to request clarification or add additional context in comments.

Comments

2

You though the first argument passed to setTimeout is a function, but it's not.

When you do:

setTimeout(hi(x), 100000);

it means:

  1. evaluate the expression hi(x) to get its value
  2. after 100000ms, if the value from previous step is

    • callable, call it (with arguments if passed)
    • otherwise evaluate it (similar to eval)

so it equals:

var ret = hi(x);
setTimeout(ret, 100000);

Apparently ret is not your function hi, but the return value of it - undefined. So setTimout(undefined, 100000) actually does nothing meaningful - eval(undefined) after 100000ms.

Strip that out, your code equals:

(function hi(x) {
    if (x > 1000) {
        return;
    } else {
        x+=1;
        hi(x);
        console.log(x);
    }
})(4)

What's this? Yes, synchronous recursive function call. That's why you see the result in console is counting down rather you expected.

The solutions, besides wrapping it in an anonymous function:

setTimeout(function () {
    hi(x);
}, 100000);

Alternatively you can also pass extra arguments to setTimeout:

setTimeout(hi, 100000, x);

Arguments passed to setTimout after the delay, will be passed in hi when invoking it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.