Question :
Review 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 with the data.
So far so good.
This request is made every three (3) seconds
Only about after about 20 runs the computer starts to crash.
The backend is in Laravel with MySQL
Testing by PostMan it returns fast and normal
Does it have anything to do with PHP?
Answer :
The recommended time is to set the timer after Ajax has finished (% w / o%), as complete
and not setTimeout
. Because Ajax is asynchronous, setInterval
will always execute the Ajax function 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 setInterval
in setTimeout
of Ajax and call the function when loading the page. In 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();