Ajax locks the computer

Asked

Viewed 211 times

4

Analyze the code below

function update(){
  $.ajax({
    url  : 'http://localhost/sistema',
    type : 'get',
    dataType : 'json',
    success : function( data ){
      console.log('Mostrar dados: '+.data.dado);
    }
  })
}


setInterval(function () { update() }, 3000);

ajax sends a 'get' request to the server that returns the data.

So far so good.

This request is made every three (3) seconds

Only that approximately after about 20 runs the computer all starts to lock.

The backend is in Laravel with Mysql

Testing by Postman he returns fast and normal

Does it have something to do with PHP?

1 answer

4


The recommended is to put the timer after the Ajax termination (complete), as setTimeout and not setInterval. That’s because, since Ajax is asynchronous, setInterval will always execute the function that calls Ajax without waiting for the previous request to be completed, and this can create a huge bottleneck of requests, overloading the server and the browser, resulting in crashes.

Put a setTimeout in the complete Ajax and call the function when loading the page. This way, a new request will only be made 3 seconds after the previous one has been completed:

function update(){
  $.ajax({
    url  : 'http://localhost/sistema',
    type : 'get',
    dataType : 'json',
    success : function( data ){
      console.log('Mostrar dados: '+.data.dado);
    },
    complete: function(){
      setTimeout(function () { update() }, 3000);
    }
  })
}

update();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.