I have created a chat room which uses ajax request to check for new message every second by using setTimeOut function, I achieved this but my only question is that, is it okey to request data from server after every second? or it may cause some problems? below is my code:
function refresh(){
setTimeout(function(){
$.ajax({
type: 'POST',
url: 'checkNewMessage.php',
data: { sender:$sender, recipient:$recipient},
success: function(response) {
$('#newComm').val(response);
if($('#newComm').val()>$('#oldComm').val()){
$.ajax({
type: 'POST',
url: 'appendNewMessage.php',
data: { sender:$sender, recipient:$recipient},
success: function(response) {
$("#chatRoom").prepend(response).fadeIn(4000);
$('#oldComm').val($('#newComm').val());
}
});
}else{}
}
});
refresh();
},1000);
}
Well, this is a question with a depends on answer.
Polling the server with timed requests is not the best way of achieving what you would like to achieve. At this place I recommend using WebSockets: https://developer.mozilla.org/en-US/docs/Glossary/WebSockets
But back to your question. It depends on your server and the load it is going to take. Lets say you have ten active users. So your server would take about 10 requests per second - not too much.
You could run a benchmark and see how many requests per second your server can handle. But handling requests is not the same like answering each request.
If you don't have so many users on your chat, you might be ok with this approach. For bigger loads I highly recommend to switch to WebSockets.