I have a question about using setInterval(); in javascript. I am developing a hospital’s (PHP/SQL, Ajax)database, now whenever a pateints test is carried out It should display a message on the main screen saying “(Pateints Name)’s Test Results updated”. I tried to do it with php script but there was no way to trigger an event directly from php script. Now I am using setInterval() for this purpose which run a function which checks the pateints database every 10 seconds and display the message when new tests are added.
setInterval(checkAndDisplayNewResults(), 10000);
My question is that ” Is it the correct way to do it? Wouldn’t it overload the server or client PC? If its not the right way then whats the alternative?
Polling a server every 10 seconds forever is rarely the right way to get updates. It’s enormously inefficient for both the client and the server and the network. You should either back the polling interval way back to a much slower time interval or implement something much smarter like a server-push solution.
One such solution that is more efficient is Comet which consists of long running server requests that will return data as soon as the server makes the data available.
HTML5 also specifies a WebSocket interface which allows the client and server to just have a socket open between the two and freely send data either way upon demand.