How to make Ajax requests every 10 seconds (except for a long poll)?

I try to get a json object request from the server every 10 seconds using this:

setInterval(function(){
  $.ajax({
    url: '/',
    success: function(data){
      //do stuff with data
    }
  });
}, 10000);

But it is not very effective. I know about a lengthy survey, but I donโ€™t think it will make a big difference. I know that I will receive new data every 10 seconds, so does that not make a long poll in the same way as setInterval in terms of efficiency?

Is browser-side caching a good solution to this problem?

The JSON object I get looks like this:

var data =  {1: {'user': 'John', 'age': '25'}, {2: {'user': 'Doe', 'age': '30'}}

[0].user [1].user, "fadeOut" "fadeIn" , . - .

ajax 10 ? , , , ?

, , , - .

+3
2

. , , AJAX 10 . , , , . , javascript, , users = new Array (user1, user2,...). , , . , , , AJAX , .

, , , AJAX, , , . . 10 . , , , . , . , . , , , .

vs setInterval, setInterval . , , , , .

var storage = new Array(user1, user2, ...); //set all your data here, generate it from your server
var lastUpdate = //set the last time you updated it, just create a date variable

function rotateUsers()
{
    //do your fade in and fade out here
}

function update()
{
    //create a new HttpRequest, and then set the url as "yoursite.com/update?lastUpdateTime="+lastUpdate;
    //Take the response data, and merge the new users list with the old one
}
setInterval('rotateUsers()',10000);
setInterval('update()',60000); //update once a minute
+6

, setInterval (fn, delay), , , , , , .

/, XHR WebSockets

0

Source: https://habr.com/ru/post/1773406/


All Articles