0

Why this code doesn't work?
I wrote This code but:

(function($){
$.fn.newsSlider = function() {
    setTimeout(function() {
        this.each( function() {
            $(this).each(function(){
                $(this).append($(this).children(":first-child").clone());
                $(this).children(":first-child").remove();
            });
        });
    }, 3000);
}

}(jQuery));

With setInterval:
http://jsfiddle.net/OmidJackson/46UNg/
Without setInterval:
http://jsfiddle.net/OmidJackson/6bKWU/

2 Answers2

0

Your problem is that this has different meaning (the window object) inside the setTimeout function literal. Check this answer for further info about this in different contexts.

The solution is to save a reference to this so you can use it inside the setTimeout.
See this example.

Community
  • 1
  • 1
sudee
  • 773
  • 9
  • 14
0

You need to store the this as it currently has a value of window

var $this = this;
setTimeout(function() {
    $this.each( function() {
        $(this).each(function(){
            $(this).append($(this).children(":first-child").clone());
            $(this).children(":first-child").remove();
        });
    });
}, 3000);
iConnor
  • 19,997
  • 14
  • 62
  • 97