0

In my case why arr is not defined? I saw the error in jsfiddle's console log. Supposed it's a gobal variable so it can be access in any function scope? http://jsfiddle.net/xgpqe4rv/3/

$(function() {

    autoSlide = setInterval(cycle(), 3000);


    arr = [{
            'logo': 'http://placehold.it/50&text=1'
        },

        {
            'logo': 'http://placehold.it/50&text=2'
        },

        {
            'logo': 'http://placehold.it/50&text=3'
        },

        {
            'logo': 'http://placehold.it/50&text=4'
        }

    ];

    $('img').attr('src', arr[0]['logo']);

    function cycle() {

        var i = 1;

        $('img').attr('src', arr[i]['logo']);

        if (i == 3) {

            i = 0;
        } else {
            i++;

        }
    };

    $('#right').click(function() {
        cycle();
    });
});
2
  • @R3tep why? give me a reason Commented Mar 9, 2015 at 15:10
  • 1
    autoSlide = setInterval(cycle(), 3000); <--- wrong Commented Mar 9, 2015 at 15:10

1 Answer 1

1
  1. You're not declaring your variables with var

  2. autoSlide = setInterval(cycle(), 3000); you are passing the return value of the function to the interval, whereas you want a function reference.

autoSlide = setInterval(cycle, 3000);

or

autoSlide = setInterval(function() { cycle() }, 3000);
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe more clear to say that he is passing the return value of the function invocation, which is probably nothing.
oh I see, what a careless mistake I did. But now I'm confused more with variable declaration. I thought without var the variable can be a global var?
@JamesLemon Yes, it is a global variable, which is exactly why it's wrong. Global variables are bad news. Moreover, global state is bad news.

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.