Aditya Sadhukhan
Aditya Sadhukhan

Reputation: 11

JavaScript not updating the DOM and crashing the browser

I have written the following HTML for a button that on click calls a function and the output of the function is written in a div in the DOM. But it is not updating the DOM anyway, but freezing the whole browser tab as well as the HTML page. Please help.

Thank you in advance

let rows = [];
let cols = [];
let secKey = "";
const generateKey = () => {
  var count = 0;
  while (count != 5) {
    let randomNumber = Math.floor((Math.random() * 10));
    if (!rows.includes(randomNumber)) {
      rows.push(randomNumber);
      count++;
    }
  }
  count = 0;
  while (count != 6) {
    let randomNumber = Math.floor((Math.random() * 10));
    if (!cols.includes(randomNumber)) {
      cols.push(randomNumber);
      count++;
    }
  }
  // put on the document
  secKey = `${cols[0]}${rows[0]}${cols[1]}${rows[1]}${cols[2]}${rows[2]}${cols[3]}${rows[3]}${cols[4]}${rows[4]}${cols[5]}`;
  document.querySelector("#sec-key").innerHTML = `Your secret key is <strong id="sec-key">${secKey}</strong>`; // #sec-key is a div where I want to show the output
};

Html:

<div class="key-container">
  <button id="generate-key" class="util-btn" onclick="generateKey()">Generate new secret key</button>
  <p class="key-holder" id="sec-key">
    <!--output is expected here-->
  </p>
  <p id="caution">*please remember the secret key for decryption</p>
</div>

Upvotes: 0

Views: 109

Answers (1)

zr0gravity7
zr0gravity7

Reputation: 3224

The problem is that upon running the function a second time, the globals likely already include the random values, and so the count variable is never incremented and the loop spins infinitely.

Either initialize the globals inside the function implementation, or use the length of the array instead of a counter. Second approach is shown below:

let rows = [];
let cols = [];
let secKey = "";
const generateKey = () => {

  while (rows.length != 5) {
    let randomNumber = Math.floor((Math.random() * 10));
    if (!rows.includes(randomNumber)) {
      rows.push(randomNumber);
    }
  }

  while (cols.length != 6) {
    let randomNumber = Math.floor((Math.random() * 10));
    if (!cols.includes(randomNumber)) {
      cols.push(randomNumber);
    }
  }
  // put on the document
  secKey = `${cols[0]}${rows[0]}${cols[1]}${rows[1]}${cols[2]}${rows[2]}${cols[3]}${rows[3]}${cols[4]}${rows[4]}${cols[5]}`;
  document.querySelector("#sec-key").innerHTML = `Your secret key is <strong id="sec-key">${secKey}</strong>`; // #sec-key is a div where I want to show the output
};

Upvotes: 4

Related Questions