greener
greener

Reputation: 5069

Error on simple javascript function using setInterval

I have this small function giving an error because i is undefined:

var i = 0
    setInterval(function(i){
        var i = ( i < $(".news-items li").length ) ? i++ : 0 ;
        $(".news-items li").hide();
        $(".news-items li:eq("+i+")").show();
    }, 1000)

Can anyone spot the problem?

Upvotes: 0

Views: 163

Answers (1)

gen_Eric
gen_Eric

Reputation: 227270

setInterval(function(i){

You're redeclaring i as a local variable in the anonymous function. Remove the i in the function's parameter list.

var i = 0
setInterval(function(){
    // Note that this will NOT update the global "i"
    // if you want it to, remove "var"
    // Also change "i++' to "i+1"
    var i = ( i < $(".news-items li").length ) ? i+1 : 0 ;
    $(".news-items li").hide();
    $(".news-items li:eq("+i+")").show();
}, 1000)

Upvotes: 2

Related Questions