0

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

2 Answers 2

1

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.

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

1 Comment

There is error in your code. It should look like this: var order = 0; function f() { order++; } $("#btn").on("click", f);
0

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);

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.