javascript node.js How to avoid While(true) in this situation? - javascript

I have read that use of 'while(true)' is a big no-no and use of 'while(condition)' or 'do...while(condition)' is recommended(1).
Can you tell me how to do that here -
while (true){
get some data;
if(condition based on data above), do something;
else(break);
} //repeat until break reached
I could use 'do...while' (see below) but that repeats the 'if' condition so this doesn't seem to be the best option -
do{
get some data; //must happen first to get info to create condition
if(condition based on data above), do something;
} while(condition based on data above);

It can be more simple like this, with an example:
var x = 0;
console.log("Entering loop");
while(true){
// always make sure to update something in your condition
// so you dont fall into an infinite loop
x++;
console.log(x); // mostly demostrative
if(x===3) break; // condition to determine when should the loop stop
}
console.log("Out of the loop");

There is no problem using while(true).
The no-no you read is because it is a potential issue that can be resulted into an infinite loop.
So if this is the case, you can use a counter to break the loop if nothing happens until that. for eg, max_attempt = 100.

Why not just do:
for(get some data; condition based on data above; get some data;) {
do something;
}
E.g.:
for(var i = Math.random(); i < .8; i = Math.random()) {
console.log(i);
}

I would use something like this:
while (condition based on data above){
get some data;
do_something;
}
Example:
while (variable_boolean == false && variable_num <= 10){
variable_2 = variable_num * 5;
}

Related

How do I make this continue iteration through the FOR loop. Stuck on index 5

I'm building Connect Four per my beginner's project for the course I'm taking. I can't get it to move on past index 5. It seems to still return true that index 5 is undefined, even though after I click it the first time, it has turned red. I thought it would, per following click, run the for loop, starting with 5 again, but that it would then return False, and go back to the next index, 4, checking that one, and so forth. I have looked up a lot and I am just stuck. I can't figure it out.
I know that the code is not complete for the long run of the game; I'm just trying to understand this step, however ugly the code might be, so that I can move on to another piece.
var gClass = $(".G")
function returnBackgroundColor(rowIndex,colIndex){
// console.log($(colIndex[rowIndex]).prop("background-color"));
// console.log(rowIndex);
return($(colIndex[rowIndex]).prop("background-color"));
}
function changeColor(row, someClass){
someClass.eq(row).css("background-color","red");
}
function checkColor(someClass){
someClass.click(function() {
for (var row = 5; row > -1; row--) {
if (returnBackgroundColor(row, someClass) === undefined){
console.log(row);
return changeColor(row, someClass);
}else {
console.log("False");
}
}
})
}
checkColor(gClass)
You can use increment instead of decrement. And it is better to use dynamic endpoint in the loop
That's because of return changeColor(row, someClass);, here you are returning from the function overall. and ending the for loop.
If you want to go to the next index just use continue, but this isn't necessary since your scope is already done
for(let i =0; i < 5; i++)
for (var row = 5; row > -1; row--) {
if (returnBackgroundColor(row, someClass) === undefined){
console.log(row);
changeColor(row, someClass);
} else {
console.log("False");
}
}
You are misusing .prop in your returnBackgroundColor function. $.prop returns html properties and will not work directly on styles. You may try something like this to compare against instead: $(colIndex[rowIndex]).css('background-color')

Creating a for loop that loops over and over =

So I have a weird problem (as I can do this using dummy code, but cannot make it work in my actual code) -
The concept is simple - I need a for loop that upon hitting its max "I" number reverts "I" to 0 again and creates a loop over and over -
DUMMY CODE:
for(i=0;i<10;i++){
console.log(i);
if(i === 10){
i = 0
}
}
Now for the longer code (sorry)
function reviewF(){
// add ID to each of the objects
reviews.forEach((e, i)=>{
e.id = i
})
// get the elements to be populated on page
var name = document.querySelector('p.name');
var date = document.querySelector('p.date');
var rating = document.querySelector('.rating_stars');
var review = document.querySelector('p.review_content_text');
// reverse the array - so the newest reviews are shown first (this is due to how the reviews where downloaded)
var reviewBack = reviews.slice(0).reverse();
// start the loop - go over each array - take its details and apply it to the elements
/**
* THIS IS WHAT I WOULD LIKE TO LOOP OVER FOREVER
*
* **/
for (let i = 0; i < reviewBack.length; i++) {
(function(index) {
setTimeout(function() {
// document.getElementById('reviews').classList.remove('slideOut')
name.classList.remove('slideOut')
date.classList.remove('slideOut')
rating.classList.remove('slideOut')
review.classList.remove('slideOut')
name.classList.add('slideIn')
date.classList.add('slideIn')
rating.classList.add('slideIn')
review.classList.add('slideIn')
name.innerHTML = reviewBack[i].aditional_info_name;
date.innerHTML = reviewBack[i].Date;
rating.innerHTML = '';
review.innerHTML = reviewBack[i].aditional_info_short_testimonial;
if(reviewBack[i].aditional_info_short_testimonial === 'none'){
reviewBack.innerHTML='';
}
var numberOfStars = reviewBack[i].aditional_info_rating;
for(i=0;i<numberOfStars;i++){
var star = document.createElement('p');
star.className="stars";
rating.appendChild(star);
}
setTimeout(function(){
// document.getElementById('reviews').classList.add('slideOut')
name.classList.add('slideOut')
date.classList.add('slideOut')
rating.classList.add('slideOut')
review.classList.add('slideOut')
},9600)
}, i * 10000)
})(i);
// should create a infinite loop
}
console.log('Loop A')
}
// both functions are running as they should but the time out function for the delay of the transition is not?
reviewF();
EDITS >>>>>>>>
Ok so I have found a hack and slash way to fix the issue - but its not dry code and not good code but it works.....
this might make the desiered effect easier to understand
reviewF(); // <<< this is the init function
// this init2 function for the reviews waits until the reviews have run then
// calls it again
setTimeout(function(){
reviewF();
}, reviews.length*1000)
// this version of the innit doubles the number of reviews and calls it after that amount of time
setTimeout(function(){
reviewF();
}, (reviews.length*2)*1000)
From trying a bunch of different methods to solve this issue something I noticed was when I placed a console.log('Finished') at the end of the function and called it twice in a row (trying to stack the functions running..... yes I know a horrid and blunt way to try and solve the issue but I had gotten to that point) - it called by console.log's while the function was still running (i.e. the set time out section had not finished) - could this have something to do with it.
My apologies for the rough code.
Any help here would be really great as my own attempts to solve this have fallen short and I believe I might have missed something in how the code runs?
Warm regards,
W
Why not simply nest this for loop inside a do/while?
var looping = True
do {
for(i=0;i<10;i++){
console.log(i);
}
if (someEndCondition) {
looping = False;
}
}
while (looping);
I would think that resetting your loop would be as simple as setting "i = 0" like in the dummy code. So try putting the following into your code at the end of the for loop:
if(i === 10){
i = 0;
}

Simple Looping In Java Script

I made a simple loop and would like to know how to carry this out.
The variable's name is Math, and it is equal to 4. I am trying to write a simple looping statement that says: "While Math is not equal to 4, await your number"
Here is the code I have so far:
var math = 2+2;
var loop = function(){
for(var i=0; i < 5; i++)
{
while (math[i] != 4)
{
console.log ("Await until you reach 4");
}
}
};
loop();
The following code will do what you presumably want:
var math = 2+2;
var loop = function(){
var i = 0;
while (i !== math) {
i++;
console.log ("Await until you reach 4");
}
}
loop();
Note that technically, the for loop in javascript (as well as in many other languages) actually is not that much different from a while loop, as the code for initialization, increment and termination is rather unrestricted. You are not even forced to have an iteration variable in you for loop.
The difference is in someone else's ease of understanding of your code (or your's after you haven't looked into you code for some time). for suggests a counted iteration of a list, while some operations to be performed while (sic!) a condition is fulfilled without which the operation make no sense or produce the wrong result.
This concept will create an endless loop, that waits for something to edit the variable.
As javascript occupies the thread its running in, all events will be waiting for this endless loop to end.
If it's part of the main GUI thread, (normal javascript) this means that your page will hang. Only use this method for webworkers, or extensions.
Instead redesign as eventhandlers, instead of a main loop
edit: having read your comments, and found out what you are trying to do:
var math = 2+2;
for(var i = 0; i < 5; i++){
if(i != math){
console.log ("Await until you reach 4");
continue
}
alert("yay")
}
or with a while loop
var math = 2+2;
var i = 0;
while(math != i){
if(i != math){
console.log ("Await until you reach 4");
}
i++;
}
alert("yay")
Maybe this is what you are trying to do:
var math = 2+2;
var loop = function(){
for(var i=0; i < 5; i++){
if(i != math){
console.log ("Await until you reach 4");
}else{
console.log("You have reached 4");
}
};
loop();
Using while
var math = 2+2;
var loop = function(){
var i=0;
while(i != math){
console.log ("Await until you reach 4");
i++;
}
};
loop();
var loop = function(math){
var i = 0;
while(i!==math){
console.log ("Await until you reach 4");
i++;
}
}
loop(2+2);

simple do/while loop infinite loop issue

Okay first off, im very new to javascript and doing some tutorials to try and learn the language. My problem is probably something incredibly simple, but i can't figure it out!
Okay so ive made a very simple do/while loop. All this should do is print "do condition, only once" a single time to the console and print "do" 5 times to the console.
However it goes into an infinite loop.. probably because im defining the variable "doCondition" in the wrong place, but i cant figure out where else logically i should place it.
Any help gratefully recieved! If you could also explain where i went wrong too, i would really appreciate it.
Many thanks,
var doWhileLoop = function(text){
var doCondition = 5;
do {
console.log("do condition, once only");
};
while(doCondition > 0){
console.log(text);
doCondition--;
}
}
doWhileLoop("do");
do.. while syntax is incorrect, in your case, it goes like
var doWhileLoop = function(text) {
var doCondition = 5;
//beginning of loop
do {
console.log(text, doCondition);
doCondition--;
} while (doCondition > 0); //end of loop
};
doWhileLoop("do");
open console....
EDIT
while loop body won't execute as condition fails
var whileLoop = function(text) {
var condition = 0;
//beginning of loop
while (condition > 0) {
console.log(text, condition);
condition--;
} //end of loop
};
whileLoop("while");
open console....
do while loop body will execute once even if condition fails
var doWhileLoop = function(text) {
var condition = 0;
//beginning of loop
do {
console.log(text, condition);
condition--;
} while (condition > 0); //end of loop
};
doWhileLoop("do while");
open console....
This is not because of variable doCondition. It is because you are writing your do-while wrong. Check this out.
var doWhileLoop = function(text){
var doCondition = 5;
do {
console.log("do condition, once only");
doCondition--;
}while(doCondition > 0)
}
doWhileLoop("do");
This is the difference between a pre-conditioned loop (while(condition) {...}) and a post-conditioned loop (do{...}while(condition);).
The main difference is that a post-conditioned loop will always run the code block at least once before evaluating the condition, whereas a pre-conditioned loop will first attempt to evaluate the condition before running its code block
In your examples you've forgotten the condition in your post-conditioned loop, so it loops for ever.
References:
do...while (post-conditioned loop)
while.... (pre-conditioned loop)
What you have isn't a single loop, but two separate loops. A do {} while() loop and a while() {} loop only differ in whether the condition is evaluated before or after each iteration.
There is no initial "do once" step in a do...while loop. Just put the code that you want to execute once before the loop:
var doWhileLoop = function(text){
var doCondition = 5;
console.log("do condition, once only");
do {
console.log(text);
doCondition--;
while (doCondition > 0);
};
doWhileLoop("do");

Run a for loop. Increment the value; exit and begin loop again with new value

I want to run a loop. I want it to excecute it 16 times like,
for (var i = 0; i <= 15; i++) {
alert(i);
}
I want this loop to run on clicking a button. But the loop should only return the first value of i and then exit. Like this,
for (var i = 0; i <= 15; i++) {
alert(i);
exit();
}
What I am confused with is, whenever I click the button I want this loop to run-only once-but with the value being incremented by one. The whole idea is to alert the i value on each click of the button but incremented by one each time. I think even my use of for loop also is not making any sense. Or is my whole logic wrong. I think I am doing something more complex where something simple like using counter will accomplish the same. Any help appreciated.
var myVal = 0;
function incrementValue(){
myVal++;
alert(myVal);
}
Just increment a variable every time you call the function.
If I am getting it right, it should be somewhat like this,
var btn_init = 0;
//on click
$(function(){
$('#your_button_id').on('click',function(){
btn_init++; //increment
alert(btn_init);
}
});
<div class="button1">click</div>
<div class="valuecontainer"></div>
<script>
var i=0;
var x=15;
$('.button1').click(function(){
if(i<x){
i++;
$('.valuecontainer').html(i);
}
else
{
alert("rechaed limit");
}
});
</script>
I guess you will find your answer here:
Count function call in JS
This is the shortest code found there though i donot completely understand this (somebody plz explain):
function myFunction() {
this.num = (this.num || 0) + 1;
if(this.num <= 15)
alert(this.num);
}

Categories