I have a notification zone that I want to be updated when someone sends a message for example using jQuery or Ajax (my database is in a soap server) I want to do the soap call every second or so, how can I do that?
3 Answers
You could use a simple setInterval structure to execute AJAX calls at predefined intervals. Something like this:
setInterval(function(){
$.get('ajax_responder.php',dataObj,function(){
// ajax callback
// here is where you would update the user with any new notifications.
});
},5000);
The previous code will execute an AJAX request every 5000 miliseconds (every 5 seconds).
References:
3 Comments
setTimeouts so they surely will not pile up.Instead of setInterval(), I would strongly suggest to use setTimeout().
If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using
window.setTimeout. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its alloted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.For such cases, a recursive
setTimeoutpattern is preferred:(function loop(){ setTimeout(function(){ // logic here // recurse loop(); }, 1000); })();In the above snippet, a named function loop is declared and is immediately executed.
loopis recursively called insidesetTimeoutafter the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.
Comments
The best way for real-time web is node.js.
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
But you can do it by setInterval or setTimeout, put an Ajax call in your interval.
var intval = setInterval( function()
{
$.get('url.php', {data1: "value1", data2: "value2"},
function(response)
{
// response
});
}, 1000);
setInterval()orsetTimeout()? As far as I know, the only way to have more than one thread in JS is with web-workers, but you don't need that for this requirement.