JQuery $ .getJSON and looping through array resetting everything

This is my current JS code:

$(function(){
$.getJSON("/get_slideshow_messages",
    function(data){
        setInterval(function(){
            $.each(data, function(i, item) {
                console.log(item.message);
            });
        }, 5000);
    }
);
});

      

I am doing a simple slideshow and the url call returns an eloquent Laravel object of the form:

return SlideshowMessages::all();

      

If I pass the log data "return":

Object, Object, Object]
 0: 
     Objectcreated_at: null
     id: "1"
     message: "test1"
     updated_at: null
     __proto__: Object
 1: Object
 2: Object
  length: 3

      

How can I loop the array correctly so that I only get one element at a time?

+3


source to share


1 answer


You need to keep a counter that changes every time that interval is called, not use each one. I haven't tested this since I don't have your dataset, but in theory this should work.



$(function(){
$.getJSON("/get_slideshow_messages",
    function(data){
        var currentSlide = 0;
        var nextSlide = function () {
                //Loop back around
                if (!data[currentSlide]) currentSlide = 0;
                console.log(data[currentSlide].message);

                //Increase our counter
                currentSlide++;
        }; 

        //render the first slide straight away
        nextSlide();

        //Set up our interval to render them every 5 seconds
        setInterval(nextSlide, 5000);
    }
);
});

      

+3


source







All Articles