0

I have a code that fetches an array of objects from the server and displays them in a list. Everything works fine here except I feel like the code is sloppy and not efficient. Could I implement setInterval somewhere in my AJAX call so I don't call setInterval at the end? Also if I call setInterval in my code how can I get the AJAX call to refresh but also display the strings I'm fetching from the server as soon as the page is opened? I am very new to AJAX and jQuery (first day trying AJAX) so as always any syntax/indentation editing is much appreciated!

function displayMessages(messages){
  $('.messages').append('<li>' + messages + '</li>');
}
function fetchMessages(){
  $.ajax({type: "GET",
  url: "https://api.parse.com/1/classes/chats",
    success: function(data) { 
      for(var i = 0 ; i < 10; i++){
        displayMessages(data.results[i].text);
        if($('.messages li').length > 10){
          $('.messages li').first().remove();
        }
      }
    }

  });
}
fetchMessages();
setInterval(fetchMessages,3000);

2 Answers2

2

You may be interested in the solution here; JavaScript: How to get setInterval() to start now?

This lets you use an anonymous function that is called immediately and then regularly on the interval:

function setIntervalAndExecute(fn, t) {
    fn();
    return setInterval(fn, t);
}

You could use it like this:

var timer = setIntervalAndExecute(function() {
    $.ajax({
        type: "GET",
        url: "https://api.parse.com/1/classes/chats",
        success: function(data) { 
            for (var i = 0; i < 10; i++) {
                displayMessages(data.results[i].text);
                var msgs = $('.messages li');
                if (msgs.length > 10) {
                    msgs.first().remove();
                }
            }
        }
    });
}, 5000);

P.S. You were also missing the 2nd argument for setInterval which is the time in milliseconds of the interval.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I got the idea of using this procedure, +1 for your effort in deep analysis (of using `return`). Took me 5 minutes to understand it. Very nice :) – Praveen Nov 09 '13 at 07:19
0

First your syntax is wrong.

setInterval(fetchMessages); //wrong

Better approach is using with a variable, so that you can pause/clear it whenever you need like

fetchMessages();
var interval = setInterval(fetchMessages, 60000);  //run every 1 minute
clearInterval(interval);  //This helps to pause the continuous function
Praveen
  • 55,303
  • 33
  • 133
  • 164