James Lemon
James Lemon

Reputation: 426

Global variable not defined in Javascript

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

Upvotes: 0

Views: 565

Answers (1)

Sterling Archer
Sterling Archer

Reputation: 22395

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

Upvotes: 1

Related Questions