Reputation: 316
I am stuck with a problem. I am trying to write some code with recursion. Each time button is clicked order get + 1 and console should print 1, 2, 3, 4 ... n, but instead it gets 1 2 2 3 3 3 3 My code:
function f(order) {
console.log(order);
order++;
$("#btn").on("click", function() {
f(order);
}
)}
f(1)
Thanks
Upvotes: 0
Views: 56
Reputation: 76
Try something like this:
var order = 0;
function f() {
order++;
}
$("#btn").on("click", f);
You don't need to pass the order as a parameter to your function if you have it in the scope your function is. This way you can have much more legible code.
Upvotes: 1
Reputation: 323
I think this is clear enough. Let me know if you need explanation.
order = 0;
function f() {
console.log(order);
order++;
}
$("#btn").on("click", f);
Upvotes: 0