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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- Carriage Return (ASCII chr 13) is missing from tex
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
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:
3 seconds intervals have been used in used before by high profile people.
If things get slow, try profiling database queries in /datasource
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.