I have a chat box using jQuery and php.
setInterval(
function(){
if($('#session_container').children().length > 0){
if(localStorage['group_id']){
var group_id = localStorage['group_id'];
var session_id = localStorage['session_id'];
var gsid = 'GSID' + group_id + session_id;
$('#chatbox').load('php/chatbox.php', {'group_id' : group_id, 'session_id' : session_id},
function(){
$('#chatbox').find('tr:even').addClass('alt');
if($('#chatbox').children().length == 0){
localStorage.clear();
window.location.replace('chatro_main.php');
}
}
);
}else{
}
}
}, 1000);
As you can see from the code above, the script runs every one second which I think is very aggressive and I think it’s also wasting power(my laptop’s battery seems to be draining faster when I was running this). Is there a better way of doing this. Something like not reloading the content while the user is on another tab on the browser window. Or something like updating only the content if another user sent a message?
If you know of another technology that could do this in a more optimal way, you could also mention it.
There are several possible answers to this question:
Don’t use
setInterval, but repeatedlysetTimeoutand adjust your timeout. The idea is, that you first try like every 10 seconds, and then increase the time, if there is no action. So the intervals would be: 10, 20, 40, message received, 10, 20, message received, 10, … You have to adjust the factor you will actually increase the timeout to fit your needs.Implement it using WebSockets (see comment of @Christian Varga)
Use node.js as server side language, which interacts with client side javascript pretty well. You can have node.js broadcast messages to all clients, so you actually have a two-way connection there (I think they use WebSockets and as fallback something like comet.js, but I am not sure, I just saw it done once)