javascript function crashes my browser - javascript

I coded a simple program which take 2 textareas and combine every single line of one textarea with all the lines in the second textarea and my browser crushes after 6000 lines.
The resul of my check needs to get to 100,000 lines.
This is the javascript code:
function go() {
var lines1 = $('#text1').val().split(/\n/);
var lines2 = $('#text2').val().split(/\n/);
var textarea1 = [];
var textarea2 = [];
var textarea3 = [];
for (var i = 0; i < lines1.length; i++) {
if (/\S/.test(lines1[i])) {
textarea1.push($.trim(lines1[i]));
}
}
for (var j = 0; j < lines2.length; j++) {
if (/\S/.test(lines2[j])) {
textarea2.push($.trim(lines2[j]));
}
}
for (var k = 0; k < lines1.length; k++) {
for (var q = 0; q < lines2.length; q++) {
textarea3.push($.trim(lines1[k] + ' ' + lines2[q]));
var msg = textarea3.join("\n");
document.getElementById('text3').value = msg;
}
}
}
This is the HTML:
<textarea name="textarea" id="text1"></textarea>
<textarea name="textarea" id="text2"></textarea>
<input type="button" value="GO!" onclick="go()">
<br />
<textarea name="textarea" id="text3"></textarea>

The problem is with this code
for (var k=0; k < lines1.length ; k++) {
for (var q=0; q < lines2.length ; q++) {
textarea3.push($.trim(lines1[k] + ' ' + lines2[q]));
var msg = textarea3.join("\n");
document.getElementById('text3').value = msg;
}
}
If there are 1K lines in textarea1 and 1K in testarea2 then you will modify the DOM (by changing the value of textarea3) 1M times which is insane. So instead of updating the DOM every time try to do it outside the loop.

Try to provide maxlength attribute in textarea and then check I think it will work.
and in your for loops first store all the content in a variable and then outside for loop write it into textarea rather than each time assigning the DOM value inside for loop.

Related

can't access value through input using button

I'm doing some exercises and come across where I can't pass the value from the input box to a function inside a script, I don't really know what I have done wrong, I tried different things but didn't really work out. How can I make it work? I want to able to enter a number then press a button so that it prints pyramid according to given number, here is my code :
window.onload = function() {
let aantalLijnen = parseInt(document.getElementById('number').value);
document.getElementById("button").onclick = stars();
function stars() {
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
You're calling stars() and assigning the result to the onclick handler.
You need to pass the function itself...
document.getElementById("button").onclick = stars;
Or just create an anonymous function directly...
document.getElementById("button").onclick = function() {
...
}
As pointed out by #j08691, you are setting the value of aantalLijnen on the page load.
Instead you want to get the value at the time the function runs, so you need to move it into the function itself...
window.onload = function() {
document.getElementById("button").onclick = function () {
let aantalLijnen = parseInt(document.getElementById('number').value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
you have to get the value from input every time you click on the button
window.onload = function () {
const numberElem = document.getElementById('number');
document.getElementById("button").addEventListener('click', stars);
function stars() {
let aantalLijnen = parseInt(numberElem.value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
Besides what already said by others
Don't use onclick handlers. Stick to cumulative listeners with addEventListener
You could use String.prototype.repeat();
Defer your script or place it right before the closing </body> tag
Learn the difference between let and const
function stars() {
const num = parseInt(document.getElementById('number').value, 10);
if (num < 2 || num > 10) return console.log("Use from 2 to 10 inclusive");
const row = '*'.repeat(num);
console.log(row)
}
document.getElementById("button").addEventListener('click', stars);
Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button>

need to change input names to input id's

I need to change a calculation from input name(s) to input id(s).
The old input name was "ef-fee".
The new id is "ef-fee_" +[i]);
The old code using input names:
<script async> //Entrance Fees
function findTotalEF(){
var arrEF = document.getElementsByName('ef-fee');
var totEF=0;
for(var i=0; i<arrEF.length; i++){
if(parseInt(arrEF[i].value)) totEF += parseInt(arrEF[i].value);}
document.getElementById('totalEF').value = totEF;
}
This is the new code which doesn't work:
<script async> //Entrance Fees
function findTotalEF(){
var totEF=0;
for (i=0; i <=48; i++)
if ($('#ef-fee_' + i > 0)) {totEF += "ef-fee_" +[i].val;} // This line is not correct. Can someone please fix it?
document.getElementById('totalEF').value = totEF;
}
Should do what you are needing
function findTotalEF() {
var totEF = 0;
for (var i = 0; i <= 48; i++) {
var $input = $('#ef-fee_' + i);
var value = parseInt($input.val()) || 0;
totEF += value > 0 ? value : 0;
}
$('#totalEF').val(totEF);
}

Javascript setInterval doesn't work

I have this code that has to be a tree with random signs. I put setInterval to change the signs every second, but nothing happens and I don't get even any error.
Someone please tell me where I made a mistake, or more :).
window.onload = intervalSetup;
function intervalSetup() {
'use strict';
setInterval(function() {
theTree();
}, 1000);
}
function theTree() {
'use strict';
var x = 8;
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
document.write(" ");
}
for (var k=0; k<=(i*2); k++) {
document.write(arraySigns[Math.floor(Math.random() * arraySigns.length)]);
}
document.write("<br>")
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
document.write(" ");
}
document.write("**<br>");
}
}
I tested the code on Google Chrome and it worked correctly.
Only had an undefined error in arraySigns.
The script has removed itself by writing to the document. That was the reason, the function was never called twice.
Funny bug, I think. :-)
The first problem was an undefined array, which was fixed in an edit.
The remaining problem was that the trees were being written to the page endlessly and it was hard to see the symbols changing.
By generating the tree in a container div which is cleared before each new tree, you can easily see that the symbols were properly random each time.
The snippet has a working example that functions by adding to the innerHTML of the treeDiv. (I took out the document fragment for readability)
'use strict';
window.onload = intervalSetup;
var arraySigns;
var treeDiv;
function intervalSetup() {
arraySigns = ["*", "^", "&", "#"];
treeDiv = document.getElementById("theTreeDiv");
setInterval(theTree, 1000);
}
function theTree() {
treeDiv.innerHTML = '';
var x = 8;
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
treeDiv.innerHTML += " ";
}
for (var k=0; k<=(i*2); k++) {
treeDiv.innerHTML += arraySigns[Math.floor(Math.random() * arraySigns.length)];
}
treeDiv.innerHTML += "<br>";
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
treeDiv.innerHTML += " ";
}
treeDiv.innerHTML += "**<br>";
}
}
<div id="theTreeDiv">
</div>

'undefined' Unexpected on Array Loop + charAt

In this code I write line by line every word of the textarea, separated by white space, but on the last word undefined appears and I don't know why
window.onload = function() {
var btn2 = document.getElementById("separar");
btn2.addEventListener("click", function() {
palavrasSeparadas();
}, false);
}
var c = new Array();
function palavrasSeparadas() {
var t2 = document.getElementById("texto").value;
for (var i = 0; i < t2.length; i++) {
//charAt retorna o caracter daquela posição
c[i] = t2.charAt(i);
}
var conteudo = "";
for (var j = 0; j <= c.length; j++) {
if (c[j] != ' ') {
conteudo += c[j];
} else {
conteudo += "<br>"
}
}
document.getElementById("msgS").innerHTML = conteudo;
}
<form id="form1" name="form1" method="post" action="">
<textarea id="texto" name="texto"></textarea>
<br>
<input type="button" id="separar" name="separar" value="Separação">
</form>
<br>
<div id="msgS"></div>
<br>
Your loop goes one value too far. With j <= c.length in the last loop execution, when j = c.length, you try to access c at c.length. But as array index starts with 0, your array is only c.length-1 long. Use j < c.length in the loop.
for (var j = 0; j < c.length; j++) {
if (c[j] != ' ') {
conteudo += c[j];
}else {
conteudo += "<br>"
}
}
In your second for loop, you use less than or equal to rather than just less than. As such, you are also trying to print the index at c.length, which is undefined. Instead, you should write:
for (var j = 0; j < c.length; j++) {
if (c[j] != ' ') {
conteudo += c[j];
}else {
conteudo += "<br>"
}
}
This is a fencepost error.

dat.GUI create multiple buttons with same name

I try to use dat.GUI to create multiple buttons all with same name "ShowCoord", is this possible? What I have currently is:
for (i = 0; i < overlay.numElements; i ++)
{
var length = overlay.elementNumVertices[i];
var subObj = {
'name' : overlay.elementNames[i],
'index' : i,
'numVertices': overlay.elementNumVertices[i],
"ShowCoord" : function(){
console.log("i is " + subObj['index']);
var verts = overlay.elementVertices[i];
for(var j = 0; j < subObj['numVertices']; j ++)
{
console.log("The coordinates are " + verts[3*j] + ", "+ verts[3*j+1] +", "+verts[3*j+2]);
}
}
};
subObjArray.push(subObj);
}
for(i = 0; i < subObjArray.length; i ++)
{
var currObj = subObjArray[i];
var subGui = gui.addFolder(currObj['name']);
subGui.add(currObj, 'numVertices');
subGui.add(currObj, "ShowCoord");
}
I now have the correct currObj['name'] and currObj['numVertices'] displayed. But all the "ShowCoord" button only contains information of the very last subObj (so console.log("i is " + subObj['index']) will print out 148 every time even if I click different button). How can I make it work? Thanks a lot!
Try moving subGui outside the for loop and modifiy you code so that you don't reassign subGui varialbe.
var subGui = new dat.GUI();
for(i = 0; i < subObjArray.length; i ++)
{
var currObj = subObjArray[i];
subGui.addFolder(currObj['name']);// <--- work on this line
subGui.add(currObj, 'numVertices');
subGui.add(currObj, "ShowCoord");
}
Otherwise it will always be redefined with the last iterated element of for loop
Note: This is just a hint, I can't conclude more from your code.

Categories

Resources