Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery setInterval() undefined function error

Hi I am relatively new to javascript and jQuery and while trying to create a function the runs in intervals of 100 milliseconds I encountered a problem.I seem to get in the console of firebug and error witch says that clasing() is not defined.This is my code:

$(document).ready(function() {
    var prev = $("img.selected").prev();
    var curent = $("img.selected");
    var next =  $("img.selected").next().length ? $("img.selected").next() : $("img:first");

    $("img").not(":first").css("display","none");

    function clasing() {
        curent.removeClass("selected");
        next.addClass("selected");
    }

    setInterval("clasing()",100);
});

What am I doing wrong here?Thank you

like image 535
user1146440 Avatar asked Mar 15 '26 04:03

user1146440


2 Answers

You have a scope problem. Your variables (prev, curent and next) are accessible inside .ready scope, such as your function clasing. But when you add this function to be called in a interval, using setInterval, this function should be in a Global scope (inside window object). Then, you should declare this function like window.clasing = function(){ ... }, but, doing this, the variables declared in .ready() scope will not be accessible running the function outside this scope, so all your variables must be in a global scope too. This should solve your problem.

However, this isn't a good programming practice, you should declare your variables inside clasing function, then they will be accessible only in function scope; And your function must be delcared outside .ready() function, and then you declare the interval inside .ready() function.

So, your code should be liek this:

function clasing(){
  var prev = $("img.selected").prev();
  var curent = $("img.selected");
  var next =  $("img.selected").next().length ? $("img.selected").next() : $("img:first");

  curent.removeClass("selected");
  next.addClass("selected");
}
$(document).ready(function() {
  $("img").not(":first").css("display","none");
  setInterval("clasing()",100);  //or just setInterval(clasing,100);
});
like image 199
Rafael Verger Avatar answered Mar 16 '26 18:03

Rafael Verger


Change setInterval("clasing()",100); to setInterval(clasing,100);

like image 32
Selvakumar Arumugam Avatar answered Mar 16 '26 16:03

Selvakumar Arumugam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!