The overhead of using setInterval to get the latest data from the database


im creating a messaging feature that gets the latest messages from a database every few seconds, basically this method does a continuous database search in order to display new messages.

example of the code:

 function getLatestActivities(){
    var ignoreMessagesArr = $("input.activityId").map(function(){ return this.value; }).get().join(",");
    var profileId = $("input#userActivityId").val();

        traditional: true,
        dataType: "json",
        type: "GET", url: "include/process.php",
            getLatestActivity: "true",
            toUser: profileId,
            ignoreMessages: ignoreMessagesArr
        success: function(data){
            $.each(data, function (i, elem) {

What I want to know is whether there is a more efficient way of performing this task, i.e. detecting a change in the database instead(???).

It sounds like you want your web app to receive data when it changes in the database, but not necessarily to send data in real time. If two way communication is required then you are looking for Web Sockets which Socket.IO will help you with server side but requires that you run a Node server. There is a Google code project that enables Web Sockets for PHP called PHPWebSocket but, if I remember right, requires that you run it in a separate process (i.e. run it from the command line). So that kind of takes care of the server part, but now you have to worry about the front-end.

Currently only FireFox and Chrome fully support Web Sockets according to CanIUse. For those browsers lacking support you need a polyfill. Here is a list of HTML5 polyfills. So Web Sockets can be sort of a mess to implement, so make sure that's what you want to do.

On the other hand if your webapp only needs to receive data then EventSource (a.k.a. Server Sent Events) is the way to go. The support is better on the front-end and you don't really have to do much on the server. Again, for less than stellar browsers you will need a polyfill, but that pretty much just means IE. See the following sites/tutorials on how to use this feature.

If none of that works there are a few options. Constant polling using some kind of repeating structure like setTimeout, long polling (a.k.a. hanging get) where the server leaves the AJAX request open until there is new data, and there's also the infinite iframe trick, or maybe even a Flash plugin that connects to the server to get data.