Search code examples
javascriptinfinite-loopcreateelement

createElement creates infinite loop


I'm really new to javascript, and coding in general, and I can't understand why this causes an infinite loop:

  let newTr = document.createElement('tr');

If I take it out, the webpage loads fine, but if I leave it in, the webpage never fully loads and my browser uses 50% of my CPU.

Here's the rest of my code:

// client-side js
// run by the browser each time your view template referencing it is loaded

console.log('hello world :o');

let arrPfcCases = [];

// define variables that reference elements on our page

const tablePfcCases = document.getElementById("tablePfcCases");
const formNewPfcCase = document.forms[0];
const caseTitle = formNewPfcCase.elements['caseTitle'];
const caseMOI = formNewPfcCase.elements['caseMOI'];
const caseInjuries = formNewPfcCase.elements['caseInjuries'];

// a helper function to call when our request for case is done
const  getPfcCaseListener = function() {
  // parse our response to convert to JSON
  arrPfcCases = JSON.parse(this.responseText);

  // iterate through every case and add it to our page
  for (var i = 0; i = arrPfcCases.length-1;i++) {
    appendNewCase(arrPfcCases[i]);
  };
}

// request the dreams from our app's sqlite database
const pfcCaseRequest = new XMLHttpRequest();
pfcCaseRequest.onload = getPfcCaseListener;
pfcCaseRequest.open('get', '/getDreams');
pfcCaseRequest.send();

// a helper function that creates a list item for a given dream
const appendNewCase = function(pfcCase) {
  if (pfcCase != null) {
  tablePfcCases.insertRow();
  let newTr = document.createElement('tr');
  for (var i = 0; i = pfcCase.length - 1; i++) {
    let newTd = document.createElement('td');
    let newText = document.createTextNode(i.value);
    console.log(i.value);
    newTd.appendChild(newText);
    newTr.appendChild(newTd);
  }

  tablePfcCases.appendChild(newTr);
  }
}

// listen for the form to be submitted and add a new dream when it is
formNewPfcCase.onsubmit = function(event) {
  // stop our form submission from refreshing the page
  event.preventDefault();
  let newPfcCase = [caseTitle, caseMOI, caseInjuries];
  // get dream value and add it to the list
  arrPfcCases.push(newPfcCase);
  appendNewCase(newPfcCase);

  // reset form 
  formNewPfcCase.reset;

};

Thanks!

P.S. There are probably a ton of other things wrong with the code, I just can't do anything else until I figure this out!


Solution

  • As an explanation, in your code

    i = pfcCase.length - 1
    

    assigned the value of pfcCase.length - 1 to i. The syntax of that part of the loop should be

    an expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed.

    The evaluation of your code made no sense.

    Evaluating

    i < pfCase.length
    

    before each iteration to check that the current index is less than the length of the array, however, works correctly.