Reputation: 79
During an API url call in my web application, my html page is crashes unexpectedly and throws a 'out of memory' error. I'm really not sure what the problem is. I am using xhr object to fetch data from server. I tested multiple hotel search api from rapid api but every single of them caused the same problem. My codes are :
JAVASCRIPT ONE
const btn4 = document.querySelector('#hotelBtn')
btn4.addEventListener('click', function showHotels(e) {
var userQuery = $('#hotelQuery').val();
const data = null;
const xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
var hotelObj = JSON.parse(this.responseText)
console.log(hotelObj)
var myContainer = document.getElementById('query_results')
for (let i = 0; hotelObj.length; i++) {
var myCol = document.createElement('div')
myCol.setAttribute('class', 'col')
var myRow = document.createElement('div')
myRow.setAttribute('class', 'row')
myRow.append(myCol)
myContainer.append(myRow)
}
}
});
xhr.open("GET", "https://booking-com.p.rapidapi.com/v1/hotels/locations?locale=en-gb&name=" + userQuery);
xhr.setRequestHeader("x-rapidapi-host", "booking-com.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "mykey");
xhr.send(data);
e.preventDefault()
})
HTML ONE
<div id="query_results">
<!-- Filled by Javascript -->
</div>
Upvotes: 0
Views: 539
Reputation: 11
In the mentioned code, the condition in the for loop implemented will be true for all iterations and hence the issue occurs.
The solution provided by @inki is the right solution since the condition block checks whether i<length
, which will be false at the end of array and exits from the loop.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
Upvotes: 1
Reputation: 79
I have replaced traditional for loop with foreach loop structure. The problem seems solved right now. In tradition for loop, the loop may executing infinite times which is causing out of memory exception
Upvotes: 0
Reputation: 1946
Looks like you have an infinite loop in your code.
You will want to check that the loop ends based on the size of the length of the array...
for (let i = 0; i < hotelObj.length; i++) {
Upvotes: 2