简体   繁体   中英

Recursion stack - Javascript

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM