Is there a better way to create asynchronous updat

2019-05-15 05:37发布

I have multiple parts of my site which check for updates every half a second, so it can alert you of messages, etc. However I feel that using $.post with a setInterval could be a bit heavy on the site. Is there an alternative method that is better recommended for these tasks?

2条回答
我命由我不由天
2楼-- · 2019-05-15 06:05

Yes, although it's not trivial.

The better approach

You can use long polling (or "comet"), which opens a connection, keeps it open for 20s or so, and the immediately re-opens it. The server can send something at any time.

Newer browsers provide websockets, which provides persistent connections.

Both are relatively complex to code so you need some kind of framework to handle things for you. Also, a connection needs to be kept open for each user, so it only really works with something lightweight like NodeJS.

The easier approach

If you want something easier to implement, I would recommend checking for updates as you suggested (it's called short polling to contrast it with long polling/websockets). You can do a simple polling solution like so:

window.setInterval(function () {
  // More lightweight than $.post
  $.get('/datasource', function () {
    /* do something */
  }); 
}, 3000);

3 seconds intervals have been used in used before by high profile people.

If things get slow, try profiling database queries in /datasource

查看更多
爷的心禁止访问
3楼-- · 2019-05-15 06:08

socket.io would be the way to go if you're using nodeJS. Otherwise, checkout this jQuery plugin, it has graceful degradation implemented even though not as comprehensive as socket.io.

查看更多
登录 后发表回答