Reputation: 8961
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)
Upvotes: 1
Views: 50
Reputation: 13838
You though the first argument passed to setTimeout
is a function, but it's not.
When you do:
setTimeout(hi(x), 100000);
it means:
hi(x)
to get its valueafter 100000ms, if the value from previous step is
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.
Upvotes: 2
Reputation: 148524
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.
Upvotes: 5