Maintaining a Queue in JavaScript

I am working and MVC4 and Return a list of objects to View as Json. Actually View makes a Ajax call to Controller to retrieve data. I need to maintain a Queue of that Object and Display them on my page in such a way each object will be displayed for 10 secs and then it will be replaced with second object in Queue. I am using following code to make an Ajax call

function GetData() {
    $.get("http://localhost:45533/Home/GetData/", function (data) {
        ProcessData(data);
        // Here i need to add [data] to Queue
    });
}

function ProcessData(data) {
    $("#myDiv").append(data.Name+ "<br/>");
}

$("#fetchBtn").click(function() {
    // Here i need to get the next object in data from Queue
});

Currently i am using button click to refresh it. Can anyone suggest how i can maintain a Queue of returned data?

Upvotes: 3

Views: 579

Answers (1)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Try this...

var arData = [];

function GetData() {
    $.get("http://localhost:45533/Home/GetData/", function (data) {
        ProcessData(data);
        // Here i need to add [data] to Queue
    });
}

function ProcessData(data) {
    arData.push(data)   //  add it to the end of the array
    $("#myDiv").append(data.Name+ "<br/>");
}

$("#fetchBtn").click(function() {
    // Here i need to get the next object in data from Queue
    var data = arData.shift();  //  get the first item of the array
});

arData.push(data) adds data to the end of the array, while arData.shift() returns the first item in the array and removes it at the same time.

Upvotes: 1

Related Questions