简体   繁体   中英

Using setTimeOut for ajax call

I want to write an chat application using ajax. So I need to check users messages table in database every 100 millisecond(0.1 second). Is any problem if i use setTimeOut to call ajax for every 100 millisecond? Any performance issue? Any pitfall or anything?

This is a very bad idea. While it might work on your local machine and a few users, it can't scale to more users easily. I suggest you to look at websockets and long polling.

A better alternative would be to use Socket.IO . It makes this task a lot easier

Socket.IO makes it cross browser solution

example from socket.io

Server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Client (browser):

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Edit:

For PHP, phpwebsocket class will be a good fit and for client side jquery plugin

JavaScript knows two sorts of timers: setInterval and setTimeOut. setInterval just fires every 100 miliseconds, setTimeOut scedules the next call 100 miliseconds after the previous. You should keep this behaviour in mind while tuning your app. You also may consider webworkers, who really do their job on a separate thread. They communicate message-based which sounds a suitable solution for your problem. The exact delay (100 miliseconds or more) is something you really need to try out. The book of John Resig shows that the smalles practical timer delay differs a lot across browsers, from 21ms (IE9) to 1ms (Opera).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM