2

I have this jQuery function that switches between different status messages (p elements) with ID's ranging from status_0 to status_5:

setTimeout(function() {
    var next_status;

    if (current_status < 5) {
        next_status = current_status++;
    } else {
        next_status = 0;
    }

    $(".status_visible").fadeOut("fast", function() {
        $("#status_"+next_status).fadeIn("fast");
    });

    //alert(next_status);

    change_status();
}, 10000);

My problem is that to start with, current_status definitely equals 0, but when it gets to my increment part, it comes out as 0 still! I tried this with a simple next_status = current_status + 1, which returned 01 instead of 1 (concatenated them), so I tried next_status = current_status++ and it returned 0 still.

Can anybody put me straight here please :)

2
  • 2
    In addition to the pre-incrementing operator suggested by Huang Tao, you could replace the entire if/else with next_status = ++current_status % 5 Commented Jul 16, 2012 at 2:55
  • @amnotiam: thanks for that, that's really helpful, and interesting. Commented Jul 16, 2012 at 3:56

3 Answers 3

13
next_status = ++ current_status;
Sign up to request clarification or add additional context in comments.

Comments

1

The expression current_status++ means, "increment current_status, and evaluate to the old value of current_status," that is, use current_status, and then increment it after you note its value.

You want, ++current_status, which means, "increment current_status, and evaluate to the new value."

Comments

-1

is your timeout method "setTimeout" going to be called multiple times? If so , you need to pass your counter as a parameter with global scope, otherwise it will be reset each time.

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.