Reputation: 233
Auto refreshing the div with ajax is hanging the browser in 10-15 seconds. I dont know what is the issue. When i check in laptop it hangs/crashes and also in mobile.
In laptop it says browser unresponsive.
The code is below:
function ajaxCall() {
$.ajax({
url: "cart_checkout.php",
success: (function (result) {
$("#resultDiv").html(result);
})
})
};
ajaxCall();
setInterval(ajaxCall, (1 * 1000));
Upvotes: 2
Views: 1616
Reputation: 17956
Your code has 2 potential problems that could cause that issue.
You should not use setInterval
here as it will trigger the AJAX call regardless of whether the last request finished. It does not take into account each requests duration and load time.
Full working example of polling an API and loading the results into an element:
function poll(element, url, frequency) {
let timeoutID
let count = 0
function _poll() {
count++
$.ajax({
url,
success: ((result) => {
element.innerHTML = `Response ${count} at ${new Date().toLocaleString()}\n${JSON.stringify(result, null, 2)}`
if(frequency)
timeoutID = setTimeout(_poll, frequency)
})
})
}
_poll()
return () => {
console.info('cancelling polling')
clearTimeout(timeoutID)
}
}
$(() => {
// Start polling every 2 seconds (from time last response was received
let cancelPolling = poll(document.getElementById('result'), 'https://api.nytimes.com/svc/search/v2/articlesearch.json', 2000)
// Cancel polling in 15 seconds
setTimeout(cancelPolling, 15000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result" />
The second issue is that dropping the HTML directly into the result div is a synchronous operation and will tie up the JavaScript thread causing it to be unresponsive. This might be fine if the payload is small (paged), but for large payloads you will see the browser hang. Another option is to return JSON instead of raw HTML, split it up into manageable chunks (~5 rows of data per chunk), then write the results to HTML using requestAnimationFrame
callbacks.
Upvotes: 1