performing long loop - javascript

i want to perform a loop that writes strings in a div without overloading. I have got a list of names in an global array called names. The array is filled with about 2500 names. Now i want to write the names in a div using ajax. But when i want to loop the names, the script is kinda overloading and stops with an alert of the client. This is my loop:
for(var i = 0; i < names.length; i++){
document.getElementById('div').innerHTML += names[i] + "<br/>";
}
I also tried to interlace the loop in smaller steps like 100 (because i thought like that the loop wouldnt overload). I also tried it with window.setTimeout("function(i)",0); with the param i, that steps 100 each time the function gets called, until i am at the length of the array names.
I know there is an easy way. But i can't find that way..... would be pleased by getting help.
Thanks

You can code it like:
document.getElementById('div').innerHTML = names.join('<br/>');
This will set the inner html in single instruction, solving the load issue.

try it this way:
var content = '';
for(var i = 0, n_length = names.length; i < n_length; i++) {
content += names[i] + "<br/>";
}
document.getElementById('div').innerHTML += content; // if the previous content should remain there
Please note that its faster, to store the abort value of a loop. Otherwise it would read the length-property of your array for each iteration of your loop (2500 x).
Also note that DOM-Manipulation is very verys slow, so its smart to reduce it to the lowest level possible. Better build your content separately and write it to the DOM once for all.

Related

Array reloop to remove previous set of array data generated

My file works just fine in the first round of loop when i try to rerun the function again. It shows the previous value of the previous loop when i try to use the value to match and after which it shows the correct value. If i run the function again and again, it keeps holding on to the value of the previous generated random value.
for (var i=0; i<9; i++)
{
var ranD = Math.floor(Math.random()*33);
if (mathStar.indexOf(ranD)== -1) {
mathStar.push(ranD);
item[i].innerHTML = mathStar[i];
}
else {
i--;
}
itemVal[i].value = mathStar[i];
}
Substitute using const and let for var within for loop to avoid creating global variables and --i could have unexpected results within the code where i++ is also used in the foor loop.
Is this the first occurrence of "mathStar"?
If this is the first place you're using mathStar, it means it gets created globally and that usually leads to confusion. In this case, take a look at this.
Looking at just this, it seems that you are not resetting your "mathStar" value. This way, any time you run this loop for the nth time, the values you have added to "mathStar" using mathStar.push(...) also occur in the list of values.

JavaScript For Loop Breaking Early

Why would a for loop terminate early in JavaScript? For some reason my outer for loop terminates after the first repetition. I am new to JavaScript but would expect something like this to work in Java.
function check(){
var elements = document.getElementById('fields').children;
var filteredMolecules = molecules;
console.log(elements.length);
for (i = 0; i < elements.length; i++) {
console.log(elements[i].id)
filterMolecules(filteredMolecules, elements[i].id, 0, 10);
}
}
function filterMolecules(molecules, parameter, lower, upper){
console.log('filtering');
var filteredMolecules = [];
for (i=0;i<molecules.length;i++){
var value = molecules[i].val()[parameter];
filteredMolecules.push(molecules[i]);
}
molecules=filteredMolecules;
}
In check(), I loop through elements which contains 22 items as shown by the first console.log(elements.length). If I remove the method filterMolecules(...) then all 22 IDs are logged. However, with the code as is, only the first id is logged.
I believe the filterMolecules method which should run elements.length number of times is causing the outer for loop to not work. Could someone please explain why this is happening. If relevant, in filterMolecules(...) the data is retrieved from Google Firebase with molecules[i].val()[parameter]. Additionally, both methods use the global variable molecules (line 3 and line 14)
When you don't declare variables in javascript you end up using globals (which can be a difficult to spot source of bugs). So here you are using the same global variable i for both loops. When you start looping thought molecules you are accidentally incrementing the counter loop of your first for. Use different variables or define them with :
for (let i=0;i<molecules.length;i++)
Which will give each loop its own version of i.
In this case, since the declarations are inside individual functions, you could use var too:
for (var i=0;i<molecules.length;i++) {
// etc.
}

JS For Loop Stopping Early after Calling Function

I have a Javascript Array that holds the contents of a page. In order to draw all the objects in the right places when the page loads I loop over the array and pull out the elements. This worked very well until I allowed the objects to have children within them.
The current array structure is
0-> {elements=[] frame={I keep the frame attributes here with key value pairs}}, 1-> {elements=[] frame={}}
However, I just started adding sub-elements to the elements array in each object. So now I have to loop through/draw each element, check to see if there are any children and if so then I have to draw them too.
The problem I'm having is that after I loop through the first 0 object and it's children the for loop stops running. Is it because I'm calling the same function multiple times? I've done that before so I don't think that's what is happening.
this.run_loop = function (spawn, dom) {
console.log(spawn)
alert(spawn.length)
for (i = 0; i < spawn.length; i++) {
console.log(spawn[i])
//alert("i one")
var newdom = dom + "_" + i;
this.synthesize_elements(spawn[i], dom, newdom)
if (spawn[i].hasOwnProperty('elements')) {
//alert("FOUND")
var newarray = spawn[i]['elements'];
if (newarray.length > 0) {
this.run_loop(newarray, newdom)
}
}
}
}
This is a little old but I encountered a similar issue and found my way here, but I figured it out and thought I'd post the solution if anyone else came across this. The issue in my case (and it looks like in your case as well though I can't be sure) was in the declaration of the for loop:
for (i = 0; i < spawn.length; i++)
You're not declaring that i is a new var. so if anything inside the
this.run_loop(newarray, newdom)
function also manipulates a counter variable called i that isn't declared a new var, it will also change the one in your outer scope, and kick you out of the loop if it goes over the length of spawn
just always declare:
for (var i; i< spawn.length; i++)
in your loops or make sure your counters are unique.

Javascript .pop() and .sort() not working right in a for loop

I'm trying to remove the last element in the array but it ends up putting the removed element back to the top of the list and some of the other elements are listed differently.
Same thing using the .sort() method. The output shows this sentence five times:
Tolstoy wrote War and Peace,Twain wrote Huckleberry Finn
var author_title = new Array(5)
author_title[0]="Tolstoy wrote War and Peace";
author_title[1]="Twain wrote Huckleberry Finn";
author_title[2]="Hardy wrote The Return of the Native";
author_title[3]="Dickens wrote A Christmas Carol";
author_title[4]="Uris wrote Exodus";
for(var count=0;count<author_title.length;count++) {
document.write(author_title.pop() + "<br>");
}
for(var count=0;count<author_title.length;count++) {
document.write(author_title.sort()+"<br>");
}
If you wanted to alter your array then use pop, writing a variable that is equivalent to array.length outside of the for loop, then setting your variable to that declared variable. You have to remember that you are changing your array every time you .pop(), thus changing the for-loop in each iteration. Also, the <br /> is for HTML so you may have just forgotten your self-closing tag on that
var length = array.length;
for( var i = 0; i > length; i++ ) {
document.write( array.pop() + "\n")
}
No part of this should work. for..in loops iterate over the keys for each properly, not the values. It's not meant for iterating over arrays. On my machine, it produces 0,1,2,etc.
You're also attempting to pop elements while iterating over the array. pop modifies the array, so your iterator will be invalidated on each iteration.
What you want is a simple for loop:
for (var i = 0; i < author_title.length; ++i) {
console.log(author_title[i]);
}

Javascript: TypeError variable is undefined

I am currently building a small web application with similar functionality across all modules. I want to code small generic functions so that all programmers next to me, call these functions and these functions return necessary but important data for them to implement their functionality. In this example, I am trying to deal with the typical "choose true or false" exercise. So from the template.php they call this function:
function checkAnswers(){
var radiobuttons = document.form1.exer1;
var correctAnswers = answers(); //this is an array of string
var checkedAnswers = checkExerciseRB(radiobuttons, 2, correctAnswers);
for(i=0; i<checkedAnswers.length; i++){
alert(checkedAnswers[i]);
}
}
Function checkExerciseRB is my generic function, it is called from checkAnswers.
function checkExerciseRB(rbuttons, opciones, correct){
var answers = new Array();
var control = 0;
for(i=0; i<rbuttons.length; i++){
var noPick="true";
for(j=0; j<opciones; j++){
if(rbuttons[control+j].checked){
if(rbuttons[control+j].value==correct[i]){
answers[i]= 1;
noPick="false";
break;
}
else{
answers[i]=2;
noPick="false";
break;
}
}
}
if(noPick=="true")
answers[i]=0;
control=control+opciones;
}
return answers;
}
It works great but while looking at my favorite browsers (FireFox, Chrome) error log it says:
TypeError: rbuttons[control + j] is undefined
Any clue on how to deal with this matter?
This probably means that control + j is greater than or equal to the length of the array rbuttons. There's no such array element as rbuttons[control + j].
You should learn how to use the JavaScript debugger in your favorite browsers! Debuggers are great. They let you watch this code run, line by line, as fast or as slow as you want, and watch how the value of control changes as you go.
You’ll watch it, and you’ll think “Oh! That line of code is wrong!”
You're looping through rbuttons.length times, but in each loop you're adding 2 to control. Using control to index your array, you're going to run past the end.
Does the index specified by control + j exist in the array? i.e: If that evaluates to 4, is there at least 5 items in the array?
Also, you should be using var i, var j, etc inside your for loop. Without it your variables are leaking into the scope this code is executed in (most likely the global scope, and that's not good) :)

Categories

Resources